如何使用Reflection在.NET中调用重载方法

Wes*_*s P 66 .net reflection overloading invoke .net-2.0

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

是的,我可以将对象转换为我的基类的实例并调用我需要的方法.最终发生,但现在,内部并发症将无法实现.

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

Hal*_*rim 107

您必须指定所需的方法:

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]);
Run Code Online (Sandbox Code Playgroud)

  • 您也可以执行Type.EmptyTypes (6认同)
  • 如果其中一个参数是通用的怎么办? (3认同)
  • 需要在"typeof(int),typeof(string)"之后编译:) (2认同)

Kei*_*ith 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 } );
Run Code Online (Sandbox Code Playgroud)

如果你以相反的方式执行此操作(即通过查找MemberInfo并调用Invoke),请注意你得到正确的 - 无参数重载可能是第一个找到的.


bar*_*tta 5

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

typeof ( Class ).GetMethod ( "Method", new Type [ 0 ] { } ).Invoke ( instance, null );
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用Type.EmptyTypes (3认同)