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)
既然你没有解释如何在没有命令属性的情况下想要属性,那么我已经做到了这一点,以便它们可以在开头.但是这段代码的要点是:
FieldOrder,-1用于没有属性的属性.(不知道你想要什么)PropertyInfoPropertyInfo[]数组.| 归档时间: |
|
| 查看次数: |
12365 次 |
| 最近记录: |