【发布时间】:2009-12-22 19:11:44
【问题描述】:
我有一个问题,在创建 List 类型的对象“oListType01”并将其分配给另一个类型为“object”的对象“oObjectType”之后,我无法再访问函数“ElementAt(1)”。我尝试使用反射,但我总是在“调用”方法中遇到异常(参数冲突)。有谁知道为什么? 米兰
MyClass01 oMy1 = new MyClass01();
oMy1._ID = "1";
MyClass01 oMy2 = new MyClass01();
oMy2._ID = "3";
IList<MyClass01> oListType01 = new List<MyClass01>();
oListType01.Add(oMy1);
oListType01.Add(oMy2);
object oObjectType = new object();
oObjectType = oListType01;
从这里 fowrads 只有对象 oObjectType 可用(在实际情况下,向上发生在单独的函数调用中)。在 VS oObjectType 中显示了我想通过反射访问的两个元素。
MethodInfo mInfo = typeof(System.Linq.Enumerable).GetMethod("ElementAt").MakeGenericMethod(typeof(object));
object oSingleObject = mInfo.Invoke(oObjectType, new object[] { 1 });
【问题讨论】:
-
你为什么首先将它分配给一个对象?如果出于某种原因必须这样做,并且如果您在编译时知道列表将始终包含 MyClass01 实例的类型,那么您为什么不将其转换回 List
,如下所示:(( List )oObjectType).ElementAt(1); -
请看一下“answer”,我在其中解释说 invoke 只能用于引用 oObjectType(不是 oListType01 也不是 MyClass01)。
标签: c# linq reflection extension-methods