本文介绍了如何调用扩展方法" ElementAt的]清单&LT的; T>与反思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题,创建对象类型名单,LT的oListType01之后; MyClass01>并将其分配给类型的另一个客体oObjectType,对象后,我无法访问任何更多的功能的ElementAt(1)。我试图通过使用反射,但我总是在得到调用的方法异常(参数冲突)。有谁知道为什么吗?
米兰

  MyClass01 oMy1 =新MyClass01(); 
oMy1._ID =1;

MyClass01 oMy2 =新MyClass01();
oMy2._ID =3;

&IList的LT; MyClass01> oListType01 =新的List< MyClass01>();

oListType01.Add(oMy1);
oListType01.Add(oMy2);

对象oObjectType =新的对象();

oObjectType = oListType01;



//从这里fowrads唯一对象oObjectType
可用(向上发生在单独//
//在真实情况下的函数调用)。在VS oObjectType
显示了我想
//每反射访问提供了两个元素

  MethodInfo的明复= typeof运算(System.Linq.Enumerable).GetMethod(ElementAt的)MakeGenericMethod(typeof运算(对象)); 


对象oSingleObject = mInfo.Invoke(oObjectType,新的对象[] {1});


解决方案

我会假设你有一个有效的理由这样做这一点,但它似乎有点不对。那这里说的是一些代码,将完成你正在尝试做的。

  MethodInfo的明复= typeof运算(System.Linq.Enumerable ).GetMethod(ElementAt的)MakeGenericMethod(typeof运算(MyClass01。)); 
对象oSingleObject = mInfo.Invoke(oObjectType,新的对象[] {oObjectType,1});

当我运行这段代码,我得到该列表中的第二个元素。


I have problem that after creating object "oListType01" of type List < MyClass01 > and after assigning it to the another objet "oObjectType " of type "object" I can not access any more function "ElementAt(1)". I tried by using reflection but I am always getting exception(parameter conflict) in "Invoke" method. Does anyone knows why ?Milan

        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;

//from here fowrads only object oObjectType //is available (upwards happens in separate //function call in the real case). In VS oObjectType shows two element which I would like //to access per reflection

        MethodInfo mInfo = typeof(System.Linq.Enumerable).GetMethod("ElementAt").MakeGenericMethod(typeof(object));


        object oSingleObject = mInfo.Invoke(oObjectType, new object[] { 1 });
解决方案

I will assume you have a valid reason to be doing this but it seems a little wrong. That said here is some code that will accomplish what you are trying to do.

MethodInfo mInfo = typeof(System.Linq.Enumerable).GetMethod("ElementAt").MakeGenericMethod(typeof(MyClass01));
object oSingleObject = mInfo.Invoke(oObjectType, new object[] { oObjectType, 1 });

When I run this code I get the second element in the List.

这篇关于如何调用扩展方法&QUOT; ElementAt的]清单&LT的; T&GT;与反思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 23:46