如何使用自定义属性属性对类的属性进行排序

Dev*_*r22 9 c# sorting attributes properties

我有一个自定义属性,我应用于类的属性.此属性用于将类的属性导出到平面文件.

属性的一个属性是FieldOrder.我需要确保导出类属性的顺序是正确的.此外,并非该类中的所有属性都具有自定义属性.

我发现这篇文章:如何根据自定义属性对通用列表进行排序?此解决方案假定所有属性都具有自定义属性,这不是我的情况.我也希望有更优雅的解决方案.

非常感谢您的帮助!

public interface IFileExport{}

public class ExportAttribute: Attribute
{
    public int FieldOrder { get; set; }
    public int FieldLength { get; set; }
    public ExportAttribute() { }
}

public class ExportClass: IFileExport
{
    [ExportAttribute( FieldOrder = 2, FieldLength = 25 )]
    public string LastName { get; set; }

    [ExportAttribute( FieldOrder=1, FieldLength=25)]
    public string FirstName { get; set; }

    [ExportAttribute( FieldOrder = 3, FieldLength = 3 )]
    public int Age { get; set; }

    public ExportClass() { }
}

public class TestClass
{
    public static List<PropertyInfo> GetPropertiesSortedByFieldOrder
                                                            (IFileExport fileExport)
    {
        //get all properties on the IFileExport object
        PropertyInfo[] allProperties = fileExport
                         .GetType()
                         .GetProperties( BindingFlags.Instance | BindingFlags.Public );
        // now I need to figure out which properties have the ExportAttribute 
        //and sort them by the ExportAttribute.FieldOrder
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:我通过ExportAttribute.FieldOrder Ascending命令属性

Kir*_*oll 28

public static List<PropertyInfo> GetPropertiesSortedByFieldOrder( IFileExport    fileExport )
{
    PropertyInfo[] allProperties = GetType()
        .GetProperties(BindingFlags.Instance | BindingFlags.Public)
        .Select(x => new 
        { 
            Property = x, 
            Attribute = (ExportAttribute)Attribute.GetCustomAttribute(x, typeof(ExportAttribute), true) 
        })
        .OrderBy(x => x.Attribute != null ? x.Attribute.FieldOrder : -1)
        .Select(x => x.Property)
        .ToArray();
}
Run Code Online (Sandbox Code Playgroud)

既然你没有解释如何在没有命令属性的情况下想要属性,那么我已经做到了这一点,以便它们可以在开头.但是这段代码的要点是:

  1. 获取属性
  2. 将它们转换为匿名类型,以便您可以轻松访问属性和属性.
  3. 按顺序排序FieldOrder,-1用于没有属性的属性.(不知道你想要什么)
  4. 将序列转换回序列 PropertyInfo
  5. 将其转换为PropertyInfo[]数组.