首页 > 解决方案 > c#如何通过反射获取派生类属性列表,先按基类属性排序,再按派生类props

问题描述

我希望从派生类中获取属性列表,我编写了一个函数来提供属性列表。我的问题是我希望属性列表包含基类的第一个属性和派生类的属性之后我该怎么做?现在我在派生中获得第一个属性,然后在基础中获得

PropertyInfo[] props = typeof(T).GetProperties();
        Dictionary<string, ColumnInfo> _colsDict = new Dictionary<string, ColumnInfo>();

        foreach (PropertyInfo prop in props)
        {
            object[] attrs = prop.GetCustomAttributes(true);
            foreach (object attr in attrs)
            {
                ColumnInfo colInfoAttr = attr as ColumnInfo;
                if (colInfoAttr != null)
                {
                    string propName = prop.Name;
                    _colsDict.Add(propName, colInfoAttr);                        
                }
            }
        }

标签: c#inheritancereflectionpropertiesderived-class

解决方案


如果您知道基类类型,您可能可以执行以下操作:

  public static Dictionary<string, object> GetProperties<Derived, Base>()
  {
        var onlyInterestedInTypes = new[] { typeof(Derived).Name, typeof(Base).Name };

        return Assembly
            .GetAssembly(typeof(Derived))
            .GetTypes()
            .Where(x => onlyInterestedInTypes.Contains(x.Name))
            .OrderBy(x => x.IsSubclassOf(typeof(Base)))
            .SelectMany(x => x.GetProperties())
            .GroupBy(x => x.Name)
            .Select(x => x.First())
            .ToDictionary(x => x.Name, x => (object)x.Name);
  }

对您来说重要的部分.OrderBy(x => x.IsSubclassOf(typeof(Base)))将订购这些属性。


推荐阅读