簡體   English   中英

使用泛型類中定義的泛型參數調用非泛型方法

[英]Invoke a non generic method with generic arguments defined in a generic class

這是我的問題;

public class MyClass<T>
{
   public void DoSomething(T obj)
   {
      ....
   }
}

我做的是:

var classType = typeof(MyClass<>);
Type[] classTypeArgs = { typeof(T) };
var genericClass = classType.MakeGenericType(classTypeArgs);
var classInstance = Activator.CreateInstance(genericClass);
var method = classType.GetMethod("DoSomething", new[]{typeof(T)});
method.Invoke(classInstance, new[]{"Hello"});

在上面的例子中,我得到的異常是:無法對ContainsGenericParameters為true的類型或方法執行后期綁定操作。

如果我嘗試使該方法通用,則會再次失敗並出現異常:MakeGenericMethod只能在MethodBase.IsGenericMethodDefinition為true的方法上調用。

我該如何調用該方法?

您正在錯誤的對象上調用GetMethod 使用綁定的泛型類型調用它,它應該工作。 這是一個完整的樣本,它可以正常工作:

using System;
using System.Reflection;

internal sealed class Program
{
    private static void Main(string[] args)
    {
        Type unboundGenericType = typeof(MyClass<>);
        Type boundGenericType = unboundGenericType.MakeGenericType(typeof(string));
        MethodInfo doSomethingMethod = boundGenericType.GetMethod("DoSomething");
        object instance = Activator.CreateInstance(boundGenericType);
        doSomethingMethod.Invoke(instance, new object[] { "Hello" });
    }

    private sealed class MyClass<T>
    {
        public void DoSomething(T obj)
        {
            Console.WriteLine(obj);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM