1.特性是一个类,它继承于Attribute。它对程序中的元素进行标注,如类型、字段、方法和属性等。 Attribute是程序代码的一部分,它不会被编译器丢弃,而且还会被编译器编译进程序集(Assembly)的元数据(Metadata)里。
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class FieldForExportAttribute : Attribute
{
public FieldForExportAttribute(string columnName, int sort = 0, int tasktype = 0)
{
ColumnName = columnName;
Sort = sort;
TaskType = tasktype;
}
public string ColumnName { get; }
public int Sort { get; }
public int TaskType { get; }
}
2、新建类,给属性、字段标注
public class UtoClass
{
public string AccpetUserID { get; set; }
[FieldForExport("发起人",65)]
public string AppProposer { get; set; }
[FieldForExport("办结时间",50)]
public string EndedDateTime { get; set; }
public string FunctionID { get; set; }
}
List<KeyValuePair<string, string>> keyValuePairs = new List<KeyValuePair<string, string>>();
var dt = GetTable(res, ref keyValuePairs,1);
private DataTable GetTable<T>(List<T> list, ref List<KeyValuePair<string, string>> keyValuePairs,int taskType=0)
{
List<T> zz= list.OrderBy(x => x.GetType().GetProperty("name")).ToList();
var dt = new DataTable("Datas");
var type = typeof(T);
var propertyInfos = (from p in type.GetProperties()
let attr = p.GetCustomAttribute<FieldForExportAttribute>()
where attr != null
&& (attr.TaskType == 0 || attr.TaskType == taskType)
orderby attr.Sort descending
select p).ToList();
dt.Columns.Add(new DataColumn("序列号", typeof(string)));
keyValuePairs.Add(new KeyValuePair<string, string>("序列号", "序列号"));
foreach (var item in propertyInfos)
{
var a = item.GetCustomAttribute<FieldForExportAttribute>();
dt.Columns.Add(new DataColumn(a.ColumnName, typeof(string)));
keyValuePairs.Add(new KeyValuePair<string, string>(a.ColumnName, a.ColumnName));
}
var index = 1;
foreach (var item in list)
{
var dr = dt.NewRow();
dr["序列号"] = index;
foreach (var p in propertyInfos)
{
var a = p.GetCustomAttribute<FieldForExportAttribute>();
dr[a.ColumnName] = p.GetValue(item)?.ToString();
}
dt.Rows.Add(dr);
index++;
}
return dt;
}
|