c# 如何通过反射获取派生 class 属性的列表,首先按基础 class 属性排序,然后派生 class 道具
c# how to get list of derived class properties by reflection, ordered by base class properties first, and then derived class props
我希望从派生的 class 中获取属性列表
我写了一个函数,给出了我的属性列表。
我的问题是我希望属性列表包含 base class 的第一个属性和 derived class 的后属性
我怎样才能做到这一点?现在我在 derived 中获得第一个属性,然后在 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);
}
}
}
如果你知道基础 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)))
,它将订购属性。
我希望从派生的 class 中获取属性列表 我写了一个函数,给出了我的属性列表。 我的问题是我希望属性列表包含 base class 的第一个属性和 derived class 的后属性 我怎样才能做到这一点?现在我在 derived 中获得第一个属性,然后在 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);
}
}
}
如果你知道基础 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)))
,它将订购属性。