【问题标题】:How to use reflection to get properties of a base class before properties of the derived class如何在派生类的属性之前使用反射来获取基类的属性
【发布时间】:2013-11-15 07:44:05
【问题描述】:
public class BaseDto
{
    public int ID{ get; set; }
}
public class Client: BaseDto
{
     public string Surname { get; set; }
     public string FirstName{ get; set; }
     public string email{ get; set; }    
}

PropertyInfo[] props = typeof(Client).GetProperties();

这将按以下顺序列出属性: 姓氏、名字、电子邮件、ID

希望属性按以下顺序显示: ID、姓氏、名字、电子邮件

【问题讨论】:

    标签: c# reflection base propertyinfo


    【解决方案1】:

    也许是这个?

    // this is alternative for typeof(T).GetProperties()
    // that returns base class properties before inherited class properties
    protected PropertyInfo[] GetBasePropertiesFirst(Type type)
    {
        var orderList = new List<Type>();
        var iteratingType = type;
        do
        {
            orderList.Insert(0, iteratingType);
            iteratingType = iteratingType.BaseType;
        } while (iteratingType != null);
    
        var props = type.GetProperties()
            .OrderBy(x => orderList.IndexOf(x.DeclaringType))
            .ToArray();
    
        return props;
    }
    

    【讨论】:

    • 我看不出这有什么问题,我不比较DeclaringType我得到它的索引并比较索引。试试看:)
    • 可惜很丑
    • @Ozzy 那么你将如何优雅地做到这一点?
    【解决方案2】:

    不确定是否有更快的方法,但首先,获取您继承的基本类型的类型。

        typeof(Client).BaseType
    

    之后,您只能使用 bindingflags 获取基本属性。

        BindingFlags.DeclaredOnly
    

    之后对客户端类型执行相同操作,并附加结果。

    【讨论】:

      【解决方案3】:

      我更喜欢基于 linq 的解决方案:

      var baseProps = typeof(BaseDto).GetProperties();
      var props = typeof(Client).GetProperties();
      
      var allProps = baseProps
         .Concat(props.Where(p => baseProps
            .Select(b => b.Name)
            .Contains(p.Name) == false));
      

      【讨论】:

      • 请注意,这不适用于多级继承。需要更多的工作和较差的性能也......
      • @SriramSakthivel 同意
      • 谢谢。就我而言,我确实使用了多级继承。
      • @stig-red 好的,此时您应该使用 SriramSakthivel 的代码。它会为你解决的。
      【解决方案4】:

      怎么样:

      Dictionary<string, PropertyInfo> _PropertyIndex = new Dictionary<string, PropertyInfo>();
      
      Type thisType = typeof(Client);
      
      foreach (PropertyInfo pi in thisType.BaseType.GetProperties())
          _PropertyIndex.Add(pi.Name.ToUpper(), pi);
      foreach (PropertyInfo pi in thisType.GetProperties())
          if( !_PropertyIndex.ContainsKey(pi.Name.ToUpper()))
              _PropertyIndex.Add(pi.Name.ToUpper(), pi);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-09
        • 1970-01-01
        • 2017-11-05
        • 2013-01-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多