请考虑以下代码:
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; }
}
我想获得所有具有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);
}
它首先获取所有公共属性,创建包含属性和属性的对象,过滤列表以仅包含属性所在的属性,按属性索引排序,最后将其转换为字典。
我假设属性定义类似于:
public class GridColumnAttribute : System.Attribute
{
public GridColumnAttribute(int index)
{
this.Index = index;
}
public int Index { get; set; }
}
附: GetCustomAttribute<T>()
是一种生活在System.Reflection.CustomAttributeExtensions
的扩展方法,因此请确保包括using System.Reflection;