如何在反射中迭代列表
我有一个名为 Students 的属性,其类型为 List
。
经过反思我可以得到学生财产的价值。
现在的问题是如何迭代学生列表。
我需要检查 StudentID [某个值] 是否在该集合中。
var collection = studentPro.GetValue(studentObj,null);
//I need to iterate like this,
foreach(var item in collection)
{
if(item.StudentID == 33)
//Do stuff
}
请帮我。
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.
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
}
Please help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您只需强制转换它:
返回给您并存储在
var
中的值是object
类型。因此,您需要先将其转换为List
,然后再尝试循环它。RANT
这就是为什么我个人不喜欢
var
,它隐藏了类型 - 除非在 VS 中你将鼠标悬停在它上面。如果它是用object
类型声明的,那么很明显我们无法迭代它。更新
为此,您可以转换为
IEnumerable
:You just need to cast it:
The value returned to you and stored in
var
is of typeobject
. So you need to cast it toList<Student>
first, before trying looping through it.RANT
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 typeobject
it was immediately obvious that we cannot iterate through it.UPDATE
In order to do that, you can cast to
IEnumerable
:试试这个
Try this
其他人建议强制转换为 List,但我认为这对您不起作用...如果您有权访问 Student 类,那么您一开始就不会使用反射。因此,只需转换为 IEnumerable,然后在循环内,您必须再次使用反射来访问集合中每个项目的任何属性。
var collection = (IEnumerable)studentPro.GetValue(studentObj,null)
Others have suggested casting to List but I will assume that this won't work for you... if you had access to the Student class, you wouldn't be using reflection to begin with. So instead, just cast to IEnumerable and then inside your loop, you'll have to use reflection again to access whatever properties you want off of each item in the collection.
var collection = (IEnumerable)studentPro.GetValue(studentObj,null)
您尝试的方法是正确的。您只需要修复代码并转换
GetValue
的返回值:The way you tried is, is the right one. You just need to fix your code and cast the return value from
GetValue
:您可以使用如下所示的方法从代理对象中创建 POCO 对象。请注意,我依靠使用 XMLIgnore 属性来打破循环引用
You can have something like below to create a POCO object out of your proxy object. Please note that I am relying on use of XMLIgnore attribute to break circular references