+-
c# – 如何通过反射调用带参数的泛型方法?
假设我有一个这样的类,包含带out参数的泛型方法:

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

从阅读答案到其他几个问题(How to use reflection to call generic Method?和Reflection on a static overloaded method using an out parameter),我想我可以通过反射调用方法,如下所示:

// 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回来了.我尝试在类型数组中使用object而不是int,但这也不起作用.

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

最佳答案

I’m still interested to know what the syntax is for specifying an array of template types, or if it’s not possible

I don’t think it’s possible to pass that kind of detailed type specification to GetMethod[s].我想如果你有一些这样的Ms要查看,你必须得到它们然后按MethodInfos和包含的对象的各种属性进行过滤,例如在你的特定情况下需要的大部分内容:

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;
点击查看更多相关文章

转载注明原文:c# – 如何通过反射调用带参数的泛型方法? - 乐贴网