我有一个应用于类属性的自定义属性,用于将该类的属性导出到平面文件。
其中属性之一是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
}
}
更新:我正在按照ExportAttribute.FieldOrder升序排序属性。