首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C# 运用反射遍历类中所有属性和其值,遇到泛型时怎么处理

2013-12-05 
C# 运用反射遍历类中所有属性和其值,遇到泛型时怎么办?我在遍历的时候,如果遇到某个泛型,如ListT,或者Di

C# 运用反射遍历类中所有属性和其值,遇到泛型时怎么办?
我在遍历的时候,如果遇到某个泛型,如List<T>,或者Dictionary<TKey,TValue>等不确定类型时,我应该怎么去获取他们所有的值呢?求大神指教。 c# 遍历泛型
[解决办法]
Test t = new Test();
var list = t.GetType().GetProperty("list").GetValue(t, null);
foreach (object o in (list as IEnumerable))
{
    Console.WriteLine(o);
}
[解决办法]


Test t = new Test();
            var list = t.GetType().GetProperty("dictionary").GetValue(t, null);
            foreach (object o in (list as IEnumerable))
            {
                var itemKey = o.GetType().GetProperty("Key").GetValue(o, null);
                Console.WriteLine(itemKey);

                var itemValue = o.GetType().GetProperty("Value").GetValue(o, null);
                foreach (object subItem in (itemValue as IEnumerable))
                    Console.WriteLine(subItem);
            }

热点排行