您的位置:首页 > 编程语言 > C#

c# 根据自定义Attribute排序

2016-02-06 09:04 609 查看
add a class:

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

}

add [ExportAttribute(FieldOrder = 2)] on the Field

[DisplayName("Department Name")]
 [ExportAttribute(FieldOrder = 2)]
public string DepartmentName {
get {
return this.Department.DepartmentName;
}
}

Get the class's filed those have the DisplayName Attribute and order by the FieldOrder DisplayName

public PropertyInfo[] GetPropertyInfoArray(Type type)
{
PropertyInfo[] props = null;
try
{
object obj = Activator.CreateInstance(type);
//props = (from r in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
//         where r.GetCustomAttribute(typeof(DisplayNameAttribute)) != null
//         select r).ToArray();

props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Select(x => new
{
Property = x,
Attribute = (ExportAttribute)Attribute.GetCustomAttribute(x, typeof(ExportAttribute), true)
})
.Where(x => x.Property.GetCustomAttribute(typeof(DisplayNameAttribute)) != null )
.OrderBy(x => x.Attribute != null ? x.Attribute.FieldOrder : -1)
.Select(x => x.Property )
.ToArray();
}
catch (Exception ex)
{
AppLogger.LogErrorOnly(ex);
}
return props;

}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: