有没有办法在.NET (2.0)中使用反射来调用重载方法?我有一个应用程序,它动态实例化从公共基类派生的类。为了兼容,这个基类包含两个同名的方法,一个带参数,另一个不带参数。我需要通过Invoke方法调用无参数方法。现在,我得到的只是一个错误,告诉我我正在尝试调用一个不明确的方法。
是的,我可以将对象转换为基类的实例,然后调用所需的方法。最终,这将会发生,但现在,内部并发症不允许这样做。
任何帮助都是最好的!谢谢。
发布于 2008-10-21 21:10:56
你必须指定你想要的方法:
class SomeType
{
void Foo(int size, string bar) { }
void Foo() { }
}
SomeType obj = new SomeType();
// call with int and string arguments
obj.GetType()
.GetMethod("Foo", new Type[] { typeof(int), typeof(string) })
.Invoke(obj, new object[] { 42, "Hello" });
// call without arguments
obj.GetType()
.GetMethod("Foo", new Type[0])
.Invoke(obj, new object[0]);
发布于 2008-10-21 21:05:23
是。调用该方法时,请传递与所需重载匹配的参数。
例如:
Type tp = myInstance.GetType();
//call parameter-free overload
tp.InvokeMember( "methodName", BindingFlags.InvokeMethod,
Type.DefaultBinder, myInstance, new object[0] );
//call parameter-ed overload
tp.InvokeMember( "methodName", BindingFlags.InvokeMethod,
Type.DefaultBinder, myInstance, new { param1, param2 } );
如果你以相反的方式这样做(例如,通过找到MemberInfo并调用Invoke),请注意你得到了正确的重载--无参数重载可能是第一个找到的。
发布于 2008-10-21 21:09:32
使用接受System.Type[]的GetMethod重载,并传递一个空Type[];
typeof ( Class ).GetMethod ( "Method", new Type [ 0 ] { } ).Invoke ( instance, null );
https://stackoverflow.com/questions/223495
复制相似问题