簡體   English   中英

通過反射調用方法失敗

[英]Call a method through reflection fails

我嘗試使用反射調用方法,但未調用方法。 下面是我的代碼:

private abstract class A<T>
{
    public abstract void DoSomething(string asd, T obj);
}

private class MyClass : A<int>
{
    public override void DoSomething(string asd, int obj)
    {
        Console.WriteLine(obj);
    }
}

static void Main(string[] args)
{
    Type unboundGenericType = typeof(A<>);
    Type boundGenericType = unboundGenericType.MakeGenericType(typeof(int));
    MethodInfo doSomethingMethod = boundGenericType.GetMethod("DoSomething");
    object instance = Activator.CreateInstance(boundGenericType);
    doSomethingMethod.Invoke(instance, new object[] {"Hello", 123});
}

我也嘗試調用通常的方法,但是也會出錯:(。

您在錯誤的類型上檢索該方法。 DoSomething方法已在MyClass實現,而不是在您綁定的通用類型上實現。

如果嘗試以下操作,將得到您想要的結果:

Type myClass = typeof(MyClass);
MethodInfo doSomethingMethod = myClass.GetMethod("DoSomething");
object instance = Activator.CreateInstance(myClass);
doSomethingMethod.Invoke(instance, new object[] { "Hello", 123 });

暫無
暫無

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

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