根据自定义属性排序

Sort according to a custom attribute

请考虑以下代码:

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 属性,创建一个包含 属性 和属性的对象,过滤列表以仅包含属性存在的属性,按属性索引排序, 最后转换成字典。

我假设属性的定义与此类似:

public class GridColumnAttribute : System.Attribute
{
    public GridColumnAttribute(int index)
    {
        this.Index = index;
    }

    public int Index { get; set; }
}

P.S。 GetCustomAttribute<T>()System.Reflection.CustomAttributeExtensions 中的扩展方法,因此请确保包含 using System.Reflection;

Try it online