简体   繁体   English

通过反射调用方法失败

[英]Call a method through reflection fails

I try to call a method using reflection but method is not called. 我尝试使用反射调用方法,但未调用方法。 Below is my code: 下面是我的代码:

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

I also tried to call the usual method, but also errors :(. 我也尝试调用通常的方法,但是也会出错:(。

You retrieve the method on a wrong type. 您在错误的类型上检索该方法。 The method DoSomething has been implemented in MyClass and not on the generic type you bound. DoSomething方法已在MyClass实现,而不是在您绑定的通用类型上实现。

If you try the following, you will the result you are looking for: 如果尝试以下操作,将得到您想要的结果:

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