繁体   English   中英

通过反思获取列表

[英]Get a list via reflection

我有一些类包含一个PropertyInfo类型的List:

public List<PropertyInfo> Properties {get; set;}

我有一个该类的实例,但不知道它在运行时是哪个类。 所以对于那个实例,在我的情况下,它被称为P ,我需要遍历上面提到的列表。 现在我可以使用以下方法获取属性的值:

var PropList = P.GetType().GetProperty("Properties").GetValue(this, null)

但是,如果我尝试循环它:

foreach (var thisProp in PropList) - I get an error.

那么,有没有其他方法可以做到这一点?

谢谢

你必须施放

var PropList = P
  .GetType()
  .GetProperty("Properties")
  .GetValue(P, null) as IEnumerable<PropertyInfo>; // notice "as ..."

// Since PropList is IEnumerable<T> you can loop over it
foreach (var thisProp in PropList) {
  ...
}

因为GetValue(...)单独返回object

在查看您的代码后,很明显

 var PropList = P.GetType().GetProperty("Properties").GetValue(this, null)

因为你得到的错误而没有返回一个不可数的。 一种可能的解决方案要解决此问题,您需要将其强制转换为Ienumerable。

 var PropList = P
 .GetType()
 .GetProperty("Properties")
 .GetValue(this, null) as IEnumerable<PropertyInfo>;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM