【发布时间】:2011-07-29 18:01:44
【问题描述】:
我有一个自定义属性应用于类的属性。此属性用于将类的属性导出到平面文件。
属性的属性之一是FieldOrder。我需要确保导出类属性的顺序正确。此外,并非类上的所有属性都具有自定义属性。
我找到了这篇文章:How do I sort a generic list based on a custom attribute? 这个解决方案假定所有属性都具有自定义属性,这不是我的情况。我也希望有更优雅的解决方案。
非常感谢您的帮助!
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 Ascending 排序属性
【问题讨论】:
-
只是一个想法,但也许做一个简单的xml序列化会更容易,然后编写一个库将简单的平面xml转换为平面文件。它可以重复使用,您可以跳过所有这些自定义属性设置工作和反射。
标签: c# sorting attributes properties