如何在迭代反思列表 [英] How to iterate the List in Reflection
问题描述
我有叫学生一个属性是类型列表与LT;学生方式>
I am having one property called Students which is of type List<Student>
.
在反思我可以让学生属性的值。
In reflection i can get the value of Students Property.
现在的问题是如何迭代学生名单。
Now the problem is How to iterate the List of Students.
我需要检查StudentID [某些值]无论是收藏。
I need to check whether StudentID [ some value ] is in that collection.
var collection = studentPro.GetValue(studentObj,null);
//I need to iterate like this,
foreach(var item in collection)
{
if(item.StudentID == 33)
//Do stuff
}
请帮我。
推荐答案
您只需要为投是:
var collection = (List<Student>) studentPro.GetValue(studentObj,null);
价值返还给您,并存储在 VAR
的类型对象
的。所以,你需要将其转换为列表<学生>
首先,试图通过它循环前
The value returned to you and stored in var
is of type object
. So you need to cast it to List<Student>
first, before trying looping through it.
这就是为什么我的亲自的不喜欢 VAR
,它隐藏了类型 - 除非VS你悬停它。如果这是一个类型声明对象
这是显而易见的,我们不能遍历它。
That is why I personally do not like var
, it hides the type - unless in VS you hover on it. If it was a declared with type object
it was immediately obvious that we cannot iterate through it.
是其良好的。但铸件应
与反思完成。在反思我们
不知道名单的类型。我们不
知道实际类型studentObj
Yes its good. But casting should be done with reflection. In reflection we dont know the type of List. We dont know the actual type of the studentObj
。为了做到这一点,就可以转换为的IEnumerable
:
In order to do that, you can cast to IEnumerable
:
var collection = (IEnumerable) studentPro.GetValue(studentObj,null);
这篇关于如何在迭代反思列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!