如何使用反射调用私有方法?如何使用、反射、方法

2023-09-02 01:20:25 作者:暖栀

有一组在我的课私有方法,我需要的一个电话动态的基础上的输入值。二者调用code和目标方法是在相同的实例。在code是这样的:

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 instance. The code looks like this:

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);
dynMethod.Invoke(this, new object[] { methodParams });

在这种情况下, GetMethod的()将不会返回私有方法。什么的BindingFlags ,我需要提供给 GetMethod的(),以便它可以找到的私有方法?

In this case, GetMethod() will not return private methods. What BindingFlags do I need to supply to GetMethod() so that it can locate private methods?

推荐答案

只要改变你的code使用重载的版 GetMethod的 接受的BindingFlags:

Simply change your code to use the overloaded version of GetMethod that accepts BindingFlags:

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, 
    BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(this, new object[] { methodParams });

这里是的BindingFlags枚举文档。