77

有没有办法在.NET(2.0)中使用反射来调用重载方法。我有一个应用程序可以动态实例化从公共基类派生的类。出于兼容性目的,该基类包含 2 个同名方法,一个带参数,一个不带参数。我需要通过 Invoke 方法调用无参数方法。现在,我得到的只是一个错误,告诉我我正在尝试调用一个模棱两可的方法。

是的,我可以将对象转换为我的基类的实例并调用我需要的方法。最终这发生,但现在,内部复杂性不允许它发生。

任何帮助都会很棒!谢谢。

4

3 回答 3

126

您必须指定所需的方法:

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-21T21:10:55.980 回答
17

是的。当您调用该方法时,传递与您想要的重载匹配的参数。

例如:

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-21T21:05:23.197 回答
5

使用采用 System.Type[] 的 GetMethod 重载,并传递一个空的 Type[];

typeof ( Class ).GetMethod ( "Method", new Type [ 0 ] { } ).Invoke ( instance, null );
于 2008-10-21T21:09:32.270 回答