C# 根据自定义属性进行排序 请考虑此代码: public class MyClass { [CustomAttributes.GridColumn(1)] public string Code { get; set; } [CustomAttributes.GridColumn(3)] public string Name { get; set; } [CustomAttributes.GridColumn(2)] public DateTime? ProductionDate { get; set; } public DateTime? ProductionExpiredDate { get; set; } [CustomAttributes.GridColumn(4)] public int ProductOwner { get; set; } }
我想为所有具有C# 根据自定义属性进行排序 请考虑此代码: public class MyClass { [CustomAttributes.GridColumn(1)] public string Code { get; set; } [CustomAttributes.GridColumn(3)] public string Name { get; set; } [CustomAttributes.GridColumn(2)] public DateTime? ProductionDate { get; set; } public DateTime? ProductionExpiredDate { get; set; } [CustomAttributes.GridColumn(4)] public int ProductOwner { get; set; } },c#,linq,data-annotations,c#-7.0,C#,Linq,Data Annotations,C# 7.0,我想为所有具有CustomAttributes.GridColumn属性的属性获取一个字典,并按照GridColumn属性中的数字对它们进行排序,并按如下方式键入它们: PropertyName Type --------------------------------- Code string ProductionDate DateTime? Name string ProductO
CustomAttributes.GridColumn
属性的属性获取一个字典,并按照GridColumn
属性中的数字对它们进行排序,并按如下方式键入它们:
PropertyName Type
---------------------------------
Code string
ProductionDate DateTime?
Name string
ProductOwner int
我怎么能做到
谢谢像这样的东西应该有用:
private IDictionary<string, Type> GetProperties<T>()
{
var type = typeof(T);
return type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Select(p => new { Property = p, Attribute = p.GetCustomAttribute<CustomAttributes.GridColumnAttribute>() })
.Where(p => p.Attribute != null)
.OrderBy(p => p.Attribute.Index)
.ToDictionary(p => p.Property.Name, p => p.Property.PropertyType);
}
另外,GetCustomAttribute()
是存在于System.Reflection.CustomAttributeExtensions
中的扩展方法,因此请确保使用System.Reflection包含代码>
public class GridColumnAttribute : System.Attribute
{
public GridColumnAttribute(int index)
{
this.Index = index;
}
public int Index { get; set; }
}