如何通过使用lambda表达式作为参数进行反射来调用方法?

jua*_*uan 5 c# generics reflection lambda

我想做这个:

MethodInfo m = myList.GetType().GetMethod("ConvertAll", System.Reflection.BindingFlags.InvokeMethod).MakeGenericMethod(typeof(object));
List<object> myConvertedList = (List<object>)m.Invoke(myList, new object[]{ (t => (object)t)});
Run Code Online (Sandbox Code Playgroud)

myList是特定类型的通用列表(应用程序未知),我想将其转换为对象列表以执行某些操作.

但是,这会失败并显示以下错误:"无法将lambda表达式转换为类型'object',因为它不是委托类型"

你能帮我找到什么问题吗?我想做一些不可能的事情吗?

有没有其他方法来实现同样的事情?

Jon*_*eet 5

lambda表达式可以转换为具有正确签名的委托类型或表达式树 - 但您需要指定它是哪种委托类型.

我觉得你的代码将是简单,如果你做这个泛型方法:

public static List<object> ConvertToListOfObjects<T>(List<T> list)
{
    return list.ConvertAll<object>(t => t);
}
Run Code Online (Sandbox Code Playgroud)

然后你只需要找到并调用方法:

MethodInfo method = typeof(Foo).GetMethod("ConvertToListOfObjects",
    BindingFlags.Static | BindingFlags.Public);
Type listType = list.GetType().GetGenericArguments()[0];
MethodInfo concrete = method.MakeGenericMethod(new [] { listType });
List<object> objectList = (List<object>) concrete.Invoke(null, 
                                                   new object[]{list});
Run Code Online (Sandbox Code Playgroud)

完整的例子:

using System;
using System.Reflection;
using System.Collections.Generic;

class Test
{
    public static List<object> ConvertToListOfObjects<T>(List<T> list)
    {
        return list.ConvertAll<object>(t => t);
    }

    static void Main()
    {
        object list = new List<int> { 1, 2, 3, 4 };

        MethodInfo method = typeof(Test).GetMethod("ConvertToListOfObjects",
            BindingFlags.Static | BindingFlags.Public);
        Type listType = list.GetType().GetGenericArguments()[0];
        MethodInfo concrete = method.MakeGenericMethod(new [] { listType });
        List<object> objectList = (List<object>) concrete.Invoke(null,
                                                    new object[] {list});

        foreach (object o in objectList)
        {
            Console.WriteLine(o);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)