简体   繁体   English

通过反思获取列表

[英]Get a list via reflection

I have some class that contains a List with a type of PropertyInfo: 我有一些类包含一个PropertyInfo类型的List:

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

And I have an instance of that class, but it is not known which class it is at the run-time. 我有一个该类的实例,但不知道它在运行时是哪个类。 So with that instance, in my case it's called P , I need to loop through the upper-mentioned list. 所以对于那个实例,在我的情况下,它被称为P ,我需要遍历上面提到的列表。 Now I can get the value of the property by using: 现在我可以使用以下方法获取属性的值:

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

But if I try to loop through it: 但是,如果我尝试循环它:

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

So, is there any other way to do this? 那么,有没有其他方法可以做到这一点?

Thanks 谢谢

You have to cast : 你必须施放

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) {
  ...
}

since GetValue(...) alone returns object . 因为GetValue(...)单独返回object

After reviewing your code it's clear that 在查看您的代码后,很明显

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

does not return an ienumerable due to which you are getting and error. 因为你得到的错误而没有返回一个不可数的。 One possible solution To fix this issue you need to cast it to Ienumerable. 一种可能的解决方案要解决此问题,您需要将其强制转换为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