c# - 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);
}
}
}
解决方案
如果您知道基类类型,您可能可以执行以下操作:
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)))
将订购这些属性。
推荐阅读
- c# - 如何修复缩放视图的凝视?
- laravel - 向 Bootstrap Modal 发出传递值
- node.js - 开玩笑单元测试返回“MongoError:拓扑被破坏”
- java - 为什么 Android Studio 在重新格式化代码时会导入完整的包
- python - DiagonalBiLSTM RuntimeError:具有多个值的张量的布尔值不明确
- java - 使用 ProcessBuilder 修复损坏的 zip 文件
- sql - SQL算法排序器
- apache-kafka - apache kafka 应用程序日志的默认位置是什么
- python - ARIMA 和 SARIMAX 可以很好地预测数据,但预测直接/统一的结果
- ios - SwiftUI:清除模态状态或重新初始化