通过反射调用方法失败

时间:2019-03-17 11:49:56

标签: c# reflection getmethod

我尝试使用反射调用方法,但未调用方法。下面是我的代码:

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});
}

我也试图调用通常的方法,但是也会出错:(。

1 个答案:

答案 0 :(得分:0)

您在错误的类型上检索了该方法。方法DoSomething已在MyClass中实现,而不是在您绑定的通用类型上实现。

如果尝试以下操作,将得到您想要的结果:

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