zoukankan      html  css  js  c++  java
  • c# 根据自定义Attribute排序

    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;
     
           }










  • 相关阅读:
    第四章 虚拟机性能监控与故障处理工具
    C++_异常5-异常规范和栈解退
    C++_异常4-将对象用作异常类型
    C++_异常3-异常机制throw try catch
    C++_异常2-返回错误码
    C++_异常1-调用abort()
    C++_类继承7-类设计回顾
    C++_类继承6-继承和动态内存分配
    C++_类继承5-抽象基类
    C++_类继承4-访问控制protected
  • 原文地址:https://www.cnblogs.com/facial/p/5183829.html
Copyright © 2011-2022 走看看