How do I use reflection to invoke a private method?

后端 未结 10 656
说谎
说谎 2020-11-22 14:05

There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same i

相关标签:
10条回答
  • 2020-11-22 14:37

    Could you not just have a different Draw method for each type that you want to Draw? Then call the overloaded Draw method passing in the object of type itemType to be drawn.

    Your question does not make it clear whether itemType genuinely refers to objects of differing types.

    0 讨论(0)
  • 2020-11-22 14:38

    Microsoft recently modified the reflection API rendering most of these answers obsolete. The following should work on modern platforms (including Xamarin.Forms and UWP):

    obj.GetType().GetTypeInfo().GetDeclaredMethod("MethodName").Invoke(obj, yourArgsHere);
    

    Or as an extension method:

    public static object InvokeMethod<T>(this T obj, string methodName, params object[] args)
    {
        var type = typeof(T);
        var method = type.GetTypeInfo().GetDeclaredMethod(methodName);
        return method.Invoke(obj, args);
    }
    

    Note:

    • If the desired method is in a superclass of obj the T generic must be explicitly set to the type of the superclass.

    • If the method is asynchronous you can use await (Task) obj.InvokeMethod(…).

    0 讨论(0)
  • 2020-11-22 14:43

    I think you can pass it BindingFlags.NonPublic where it is the GetMethod method.

    0 讨论(0)
  • 2020-11-22 14:47

    BindingFlags.NonPublic will not return any results by itself. As it turns out, combining it with BindingFlags.Instance does the trick.

    MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, 
        BindingFlags.NonPublic | BindingFlags.Instance);
    
    0 讨论(0)
提交回复
热议问题