![](/img/trans.png)
[英]C# Reflection: How to get the properties of the derived class from the base class
[英]c# how to get list of derived class properties by reflection, ordered by base class properties first, and then derived class 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);
}
}
}
如果您知道基类类型,您可能可以执行以下操作:
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)))
它将对属性进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.