gpt4 book ai didi

c# - 如何在反射中迭代列表

转载 作者:可可西里 更新时间:2023-11-01 08:20:10 25 4
gpt4 key购买 nike

我有一个名为 Students 的属性,类型为 List<Student> .

通过反射我可以得到 Students Property 的值。

现在的问题是如何迭代学生列表。

我需要检查 StudentID [some value] 是否在该集合中。

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中类型为 object .所以你需要将它转换为 List<Student>首先,在尝试循环之前。

咆哮

这就是为什么我个人不喜欢var ,它隐藏了类型——除非在 VS 中你将鼠标悬停在它上面。如果它是用 object 类型声明的很明显我们不能迭代它。


更新

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 :

var collection = (IEnumerable) studentPro.GetValue(studentObj,null);

关于c# - 如何在反射中迭代列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5949688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com