如何通过reflection访问Generic.List索引?

好吧,我有一个类,我传递一个对象作为属性。

我传递的对象是List

在我的class级我试图通过reflection访问对象索引,但我不能!

例:

这节课的作品我刚刚写下了我想给你看的部分,我需要帮助。

 class MyClass { private object _recordSet; public object RecordSet { get { return _recordSet; } set { _recordSet = value; } } public string Draw() { system.reflection.Assembly asem = system.reflection.Assembly.getAssembly(_dataSource.GetType()); object instance; instance = asem.CreateInstance(_dataSource.GetType().UnderlyingSystemType.FullName); //to access de Count of my List int recordcount = int.Parse(_dataSource.GetType().GetProperty("Count").GetValue(_dataSource,null)); //i need to do a for(int cont = 0; cont < recordCount; cont++) { _dataSource[cont].Name; // <-- THIS PART IS NOT WORKING!!! because i cant access the Index Directly.... WHAT TO DO!! ??? } } } 

如果您正在使用reflection(因此使用大量object ),为什么不直接转换为IList (非generics)呢?

 IList list = (IList)actualList; object foo = list[17]; 

另外 – 对于带有Count的原始代码,你不是指int.Parse – 你应该只是转换(因为我们希望Count是一个int )。

只需先将对象转换为列表,此处不需要reflection。