如何使用反射来调用私有方法? [英] How do I use reflection to invoke a private method?
问题描述
我的类中有一组私有方法,我需要根据输入值动态调用一个.调用代码和目标方法都在同一个实例中.代码如下所示:
MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);dynMethod.Invoke(this, new object[] { methodParams });
在这种情况下,GetMethod()
不会返回私有方法.我需要向 GetMethod()
提供什么 BindingFlags
以便它可以定位私有方法?
只需更改您的代码即可使用重载的 接受 BindingFlags 的 GetMethod
版本:
MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType,BindingFlags.NonPublic |BindingFlags.Instance);dynMethod.Invoke(this, new object[] { methodParams });
这是 BindingFlags 枚举文档.>
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 });
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?
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 });
Here's the BindingFlags enumeration documentation.
这篇关于如何使用反射来调用私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!