[英]c# how to get list of derived class properties by reflection, ordered by base class properties first, and then derived class props
i am looking to get a list of properties from a derived class i wrote a function that gives my a list of properties.我希望从派生类中获取属性列表,我编写了一个函数,该函数给出了我的属性列表。 my problem is that i want the list of properties to contain first properties of base class and after properties of derived class how can i do this?我的问题是我希望属性列表包含基类的第一个属性和派生类的属性之后我该怎么做? now i get first properties in derived and then of base现在我得到派生的第一个属性,然后是基的
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);
}
}
}
If you know the base class type, you can probably do something like this:如果您知道基类类型,您可能可以执行以下操作:
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);
}
The important part for you being .OrderBy(x => x.IsSubclassOf(typeof(Base)))
which will order the properties.对您来说重要的部分是.OrderBy(x => x.IsSubclassOf(typeof(Base)))
它将对属性进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.