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

时间:2008-10-21 21:02:44

标签: .net reflection .net-2.0 invoke overloading

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

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

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

3 个答案:

答案 0 :(得分:105)

您必须指定所需的方法:

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]);

答案 1 :(得分:16)

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

例如:

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),请注意你得到正确的 - 无参数重载可能是第一次找到。

答案 2 :(得分:5)

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

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