本文翻譯自: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);