【问题标题】:Calling generic method using reflection in .NET [duplicate]在.NET中使用反射调用泛型方法[重复]
【发布时间】:2011-06-01 16:13:27
【问题描述】:

我有一个问题。是否可以在 .NET 中使用反射调用泛型方法? 我尝试了以下代码

var service = new ServiceClass();
Type serviceType = service.GetType();
MethodInfo method = serviceType.GetMethod("Method1", new Type[]{});
method.MakeGenericMethod(typeof(SomeClass));
var result = method.Invoke(service, null);

但它会抛出以下异常“不能对 ContainsGenericParameters 为 true 的类型或方法执行后期绑定操作。”

【问题讨论】:

    标签: .net generics reflection


    【解决方案1】:

    您没有使用MakeGenericMethod 的结果 - 这不会改变您调用它的方法;它返回另一个表示构造方法的对象。你应该有类似的东西:

    method = method.MakeGenericMethod(typeof(SomeClass));
    var result = method.Invoke(service, null);
    

    (当然也可以使用不同的变量)。

    【讨论】:

    • 太棒了!现在可以了。我相当愚蠢的错...
    • 我也有同样的问题,没有意识到MakeGenericMethod 是一个函数,而不是一个 void 方法,我敢肯定这也是 ha_t 的问题。
    • 我也犯了同样的错误,但这是因为我插入了行来分配 MakeGenericMethod 的结果,但忘记更改调用代码以使用新的返回值。
    • 第一个谷歌点击 :) 我爱你!
    • @kuldeep:您应该对代码进行基准测试以找出影响。在不了解您的系统的更多信息的情况下对影响做出预测是愚蠢的。
    【解决方案2】:

    你需要说

    method = method.MakeGenericMethod(typeof(SomeClass));
    

    至少,最好是

    var constructedMethod = method.MakeGenericMethod(typeof(SomeClass));
    constructedMethod.Invoke(service, null);
    

    MethodInfo 的实例是不可变的。

    这与

    的概念相同
    string s = "Foo ";
    s.Trim();
    Console.WriteLine(s.Length);
    string t = s.Trim();
    Console.WriteLine(t.Length);
    

    导致

    4
    3
    

    在控制台上打印。

    顺便说一下,你的错误信息

    “不能对 ContainsGenericParameterstrue 的类型或方法执行后期绑定操作。”

    如果您认为method 仍然包含泛型参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 2014-11-27
      相关资源
      最近更新 更多