[英]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.