如何通过反射调用一个没有参数的泛型方法

本文关键字:一个 参数 泛型方法 反射 何通过 调用 | 更新日期: 2023-09-27 18:25:30

假设我有一个这样的类,包含一个带有out参数的泛型方法:

public class C
{
    public static void M<T>(IEnumerable<T> sequence, out T result)
    {
        Console.WriteLine("Test");
        result = default(T);
    }
}

通过阅读其他几个问题的答案(如何使用反射来调用泛型方法?以及使用out参数对静态重载方法的反射),我认为我可能能够通过反射调用该方法,如下所示:

// get the method
var types = new[] { typeof(IEnumerable<int>), typeof(int).MakeByRefType() };
MethodInfo mi = typeof(C).GetMethod(
    "M", BindingFlags.Static, Type.DefaultBinder, types, null);
// convert it to a generic method
MethodInfo generic = mi.MakeGenericMethod(new[] { typeof(int) });
// call it
var parameters = new object[] { new[] { 1 }, null };
generic.Invoke(null, parameters);

但是mi返回为空。我已经尝试在types数组中使用object而不是int,但这也不起作用。

在调用MakeGenericMethod之前,如何为泛型方法指定类型(out参数所需)?

如何通过反射调用一个没有参数的泛型方法

这将允许您调用方法:

MethodInfo mi = typeof(C).GetMethod("M");
MethodInfo generic = mi.MakeGenericMethod(new[] { typeof(int) });
var parameters = new object[] { new[]{1},null};
generic.Invoke(null, parameters);

并获取输出参数:

Console.WriteLine((int)parameters[1]); //will get you 0(default(int)).

我仍然很想知道指定模板类型数组的语法是什么,或者是否不可能

我认为不可能将这种详细的类型规范传递给GetMethod[s]。我认为,如果你有很多这样的M要查看,你必须将它们全部获取,然后根据MethodInfo和所包含对象的各种属性进行过滤,例如,在你的特定情况下,尽可能多地进行过滤:

var myMethodM =
    // Get all the M methods
    from mi in typeof(C).GetMethods()
    where mi.Name == "M"
    // that are generic with one type parameter
    where mi.IsGenericMethod
    where mi.GetGenericArguments().Length == 1
    let methodTypeParameter = mi.GetGenericArguments()[0]
    // that have two formal parameters
    let ps = mi.GetParameters()
    where ps.Length == 2
    // the first of which is IEnumerable<the method type parameter>
    where ps[0].ParameterType.IsGenericType
    where ps[0].ParameterType.GetGenericTypeDefinition() == typeof(IEnumerable<>)
    where ps[0].ParameterType.GetGenericArguments()[0] == methodTypeParameter
    // the second of which is ref <the method type parameter>
    where ps[1].ParameterType.IsByRef
    where ps[1].ParameterType.GetElementType() == methodTypeParameter
    select mi;

您已经传递了将查找M<T>(IEnumerable<int>, ref int)的参数
您需要找到M(IEnumerable<T>, ref T)refout之间的区别仅存在于C#语言中;反射只有ref)。

我不知道该怎么通过;你可能需要循环所有的方法才能找到它。

在一个无关的问题上,你需要通过更多的BindingFlags:

BindingFlags.Public | BindingFlags.Static

这是一个众所周知的问题;要找到方法,你需要知道它的类型参数,但如果不首先知道方法,你就不可能知道其类型参数。。。

一个明显但不雅的解决方案是遍历所有方法,直到找到合适的方法。

另一个选择是利用Linq表达式API:

public static MethodInfo GetMethod(Expression<Action> expr)
{
    var methodCall = expr.Body as MethodCallExpression;
    if (methodCall == null)
        throw new ArgumentException("Expression body must be a method call expression");
    return methodCall.Method;
}

...
int dummy;
MethodInfo mi = GetMethod(() => C.M<int>(null, out dummy));