【发布时间】: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<>).MakeGenericType(typeof(int))创建了一个A<int>,但A<int>是一个抽象类。Activator.CreateInstance(typeof(A<int>))是不可能的。将其更改为使用MyClass实际上会起作用:dotnetfiddle.net/Widget/j7r96C
标签: c# reflection getmethod