[英]Using reflection return a list of objects from Property.GetValue
使用PropertyInfo.GetValue方法时,我需要检索对象列表。 我不知道它将是哪种类型。 我的代码如下所示:
public IEnumerable<Error> FindErrors(object obj)
{
var errors = new List<Error>();
errors.AddRange(Validate(obj));
List<PropertyInfo> properties = obj.GetType().GetProperties().Where(p => !p.PropertyType.IsByRef).ToList();
foreach (var p in properties)
{
if (IsList(p))
{
// This line is incorrect? What is the syntax to get this to be correcT?????
List<object> objects = p.GetValue(obj, null);
foreach (object o in objects)
{
errors.AddRange(FindErrors(o));
}
}
else
{
errors.AddRange(FindErrors(p.GetValue(obj, null)));
}
}
return errors;
}
我的问题是我不确定获取该列表的语法是什么,因为该行代码当前不正确。 如何获得该对象列表?
每个List<T>
都是List<object>
并不是真的。 您可能应该检查该类型是否实现了非泛型 IList
并改为使用它:
var objects = p.GetValue(obj, null) as IList;
if(objects != null) {...}
您可以通过IList
foreach
等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.