How to use Reflection to Invoke an Overloaded Method in .NET

前端 未结 3 1510
無奈伤痛
無奈伤痛 2020-12-08 03:46

Is there a way to Invoke an overloaded method using reflection in .NET (2.0). I have an application that dynamically instantiates classes that have been derived from a comm

相关标签:
3条回答
  • 2020-12-08 04:17

    Yes. When you invoke the method pass the parameters that match the overload that you want.

    For instance:

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

    If you do this the other way round(i.e. by finding the MemberInfo and calling Invoke) be careful that you get the right one - the parameter-free overload could be the first found.

    0 讨论(0)
  • 2020-12-08 04:22

    Use the GetMethod overload that takes a System.Type[], and pass an empty Type[];

    typeof ( Class ).GetMethod ( "Method", new Type [ 0 ] { } ).Invoke ( instance, null );
    
    0 讨论(0)
  • 2020-12-08 04:23

    You have to specify which method you want:

    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]);
    
    0 讨论(0)
提交回复
热议问题