[英]Using reflection return a list of objects from Property.GetValue
I need to retrieve a list of objects when using the PropertyInfo.GetValue method. 使用PropertyInfo.GetValue方法时,我需要检索对象列表。 I do not know what type of list it will be. 我不知道它将是哪种类型。 My code looks like this: 我的代码如下所示:
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;
}
My problem is I am not sure what the syntax should be to get that List because that line of code is currently incorrect. 我的问题是我不确定获取该列表的语法是什么,因为该行代码当前不正确。 How can I get that list of objects? 如何获得该对象列表?
It is not true that every List<T>
is a List<object>
. 每个List<T>
都是List<object>
并不是真的。 You should probably check whether the type implements the non-generic IList
and use that instead: 您可能应该检查该类型是否实现了非泛型 IList
并改为使用它:
var objects = p.GetValue(obj, null) as IList;
if(objects != null) {...}
You can foreach
etc over an IList
您可以通过IList
foreach
等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.