我有以下类(class):
public class BaseDataEntity
{
private List<string> _Changes = new List<string>();
public IEnumerable<string> GetChanges()
{
return _Changes;
}
public bool HasDataChanged
{
get { return (GetChanges().Count() > 0); }
}
public bool HasChildRecords
{
get { return (GetType().GetChildRecords().Count() > 0); }
}
}
public class ChildRecords : IList<T> where T : BaseDataEntity
{
}
还有一些辅助方法:
public static PropertyInfo[] GetChildRecords(this Type aType)
{
return aType.GetProperties().Where(pi => pi.IsChildRecords()).ToArray();
}
public static bool IsChildRecords(this PropertyInfo info)
{
return (info.GetCustomAttributes(typeof(ChildRecordsAttribute), false).Length > 0);
}
我想做的是使用反射实现一个名为 HaveChildRecordsChanged 的属性。我的问题是如何使用反射来检查任意深度的所有 ChildRecords 的 HasDataChanged 属性?
我尝试过类似的方法:
var isChanged = false;
foreach (var info in GetType().GetChildRecords())
{
var childRecordObject = info.GetValue(this, null);
var childRecords = childRecordObject as ChildRecords<BaseDataEntity>; //cannot unbox this, it evaluates as null
if (null != childRecords && childRecords.Any(x => x.HasDataChanged))
{
isChanged = true; //never hit
}
}
return isChanged;
最佳答案
ChildRecords<T>
是通用的,所以 ChildRecords<Company>
无法转换为 ChildRecords<BaseDataEntity>
。
由于您已经过滤了标有 ChildRecordsAttribute
的属性最简单的解决方案是转换为 IEnumerable
并使用OfType<BaseDataEntity>()
var childRecords = childRecordObject as IEnumerable; // IList<T> will be IEnumerable
if (null != childRecords && childRecords.OfType<BaseDataEntity>().Any(x => x.HasDataChanged))
{
isChanged = true;
}
关于c# - 递归地使用泛型反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48447583/