How do I use reflection to invoke a private method?

后端 未结 10 867
说谎
说谎 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: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(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(…).

提交回复
热议问题