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

本文翻译自:How do I use reflection to invoke a private method?

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. 在这种情况下, GetMethod()不会返回私有方法。 What BindingFlags do I need to supply to GetMethod() so that it can locate private methods? 我需要为GetMethod()提供哪些BindingFlags才能找到私有方法?


#1楼

参考:https://stackoom.com/question/ZEZ/如何使用反射来调用私有方法


#2楼

BindingFlags.NonPublic


#3楼

我认为你可以将它传递给BindingFlags.NonPublic就是GetMethod方法。


#4楼

Are you absolutely sure this can't be done through inheritance? 你绝对相信这不能通过继承吗? Reflection is the very last thing you should look at when solving a problem, it makes refactoring, understanding your code, and any automated analysis more difficult. 反思是解决问题时应该注意的最后一件事,它会使重构,理解代码以及任何自动分析变得更加困难。

It looks like you should just have a DrawItem1, DrawItem2, etc class that override your dynMethod. 看起来你应该只有一个DrawItem1,DrawItem2等类来覆盖你的dynMethod。


#5楼

Simply change your code to use the overloaded version of GetMethod that accepts BindingFlags: 只需更改代码即可使用接受BindingFlags的重载GetMethod

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

Here's the BindingFlags enumeration documentation . 这是BindingFlags枚举文档


#6楼

BindingFlags.NonPublic will not return any results by itself. BindingFlags.NonPublic不会自行返回任何结果。 As it turns out, combining it with BindingFlags.Instance does the trick. 事实证明,将它与BindingFlags.Instance结合起来可以解决问题。

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, 
    BindingFlags.NonPublic | BindingFlags.Instance);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章