gpt4 book ai didi

c# - 如何用反射调用List的扩展方法 "ElementAt"?

转载 作者:太空狗 更新时间:2023-10-29 20:15:21 25 4
gpt4 key购买 nike

我遇到的问题是,在创建类型为 List < MyClass01 > 的对象“oListType01”并将其分配给类型为“object”的另一个对象“oObjectType”之后,我无法再访问任何函数“ElementAt(1)”。我尝试使用反射,但我总是在“Invoke”方法中遇到异常(参数冲突)。有谁知道为什么?米兰

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;

从这里开始,只有对象 oObjectType 可用(在实际情况下,向上发生在单独的函数调用中)。在 VS oObjectType 中显示了两个我想每次反射访问的元素。

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

最佳答案

我会假设你有正当理由这样做,但它似乎有点不对。也就是说,这里有一些代码可以完成您正在尝试做的事情。

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

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

关于c# - 如何用反射调用List<T>的扩展方法 "ElementAt"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1948506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com