【问题标题】:Call a method through reflection fails通过反射调用方法失败
【发布时间】:2019-08-07 22:57:14
【问题描述】:

我尝试使用反射调用方法,但没有调用方法。以下是我的代码:

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

我也试过调用常用方法,但也报错:(。

【问题讨论】:

  • typeof(A&lt;&gt;).MakeGenericType(typeof(int)) 创建了一个A&lt;int&gt;,但A&lt;int&gt; 是一个抽象类。 Activator.CreateInstance(typeof(A&lt;int&gt;)) 是不可能的。将其更改为使用 MyClass 实际上会起作用:dotnetfiddle.net/Widget/j7r96C

标签: c# reflection getmethod


【解决方案1】:

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

如果您尝试以下操作,您将得到您正在寻找的结果:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多