c#如何通过反射获取派生类属性的列表,先按基类属性排序,然后按派生类道具

时间:2018-10-04 11:34:00

标签: c# inheritance reflection properties derived-class

我正在寻找派生类的属性列表 我写了一个函数,提供了我的属性列表。 我的问题是我希望属性列表包含基类的第一个属性以及派生类的后属性 我怎样才能做到这一点?现在我先获得派生属性,然后获得基础属性

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

1 个答案:

答案 0 :(得分:1)

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

  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)))对您来说很重要,它将对属性进行排序。