通过反射访问集合 [英] Accessing a Collection Through Reflection

查看:178
本文介绍了通过反射访问集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法迭代(通过foreach优选)使用反射集合?我使用反射迭代对象中的属性,当程序获得一个类型是一个集合,我想它迭代集合的内容,并能够访问集合中的对象。

Is there a way to iterate (through foreach preferably) over a collection using reflection? I'm iterating over the properties in an object using reflection, and when the program gets to a type that is a collection, I'd like it to iterate over the contents of the collection and be able to access the objects in the collection.

此时,我对所有属性设置了一个属性,并在属性集合上设置了IsCollection标志为true。我的代码检查这个标志,如果它是真的,它获得类型使用反射。有没有办法调用GetEnumerator或者Items在集合上能够迭代项目?

At the moment I have an attribute set on all of my properties, with an IsCollection flag set to true on the properties that are collections. My code checks for this flag and if it's true, it gets the Type using reflection. Is there a way to invoke GetEnumerator or Items somehow on a collection to be able to iterate over the items?

推荐答案

问题,但不是使用反射,我最终只是检查它是否IEnumerable。所有集合都实现了这一点。

I had this issue, but instead of using reflection, i ended up just checking if it was IEnumerable. All collections implement that.

if (item is IEnumerable)
{
    foreach (object o in (item as IEnumerable))
    {

    }
} else {
   // reflect over item
}

这篇关于通过反射访问集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆