How do I use reflection to invoke a private method?

后端 未结 10 671
说谎
说谎 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:35

    Invokes any method despite its protection level on object instance. Enjoy!

    public static object InvokeMethod(object obj, string methodName, params object[] methodParams)
    {
        var methodParamTypes = methodParams?.Select(p => p.GetType()).ToArray() ?? new Type[] { };
        var bindingFlags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
        MethodInfo method = null;
        var type = obj.GetType();
        while (method == null && type != null)
        {
            method = type.GetMethod(methodName, bindingFlags, Type.DefaultBinder, methodParamTypes, null);
            type = type.BaseType;
        }
    
        return method?.Invoke(obj, methodParams);
    }
    

提交回复
热议问题