How to invoke a non-public method through Reflection without worrying about the method visibility?

坚强是说给别人听的谎言 提交于 2020-01-05 08:56:28

问题


I'm just testing reflection things for curiosity and I'm trying to invoke a private method but I can't find it because is Private.

But what I really would like to know is if the visibility of the method could be automatically retrieved in the reflection search to don't worry about if the method to invoke is private, shared, friend, public etc... so there is a BindingFlags flags combination to be able to invoke a method indifferently of which is the method visibility?, I mean without worrying about the method visibility.

Here is my code:

Public Class Form1

Private Shadows Sub Load() Handles MyBase.Load

    Dim Method As System.Reflection.MethodInfo = Me.GetType().GetMethod("Test")

    If Method IsNot Nothing Then
        Method.Invoke(Me, BindingFlags.InvokeMethod Or BindingFlags.NonPublic, Nothing,
                      New Object() {"Hello World!", Type.Missing}, CultureInfo.InvariantCulture)
    Else
        MsgBox("Method not found or maybe is not public.")
    End If

End Sub

Private Sub Test(ByVal Value As String, Optional ByVal Value2 As Integer = 1)
    MsgBox(Value)
End Sub

End Class

回答1:


The BindingFlags values Public and NonPublic are not mutually exclusive. Each one just means members with that access level are to be included in the search. If you want to include both public and non-public members in the search then you simply include both BindingFlags values.

BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic

Here's a quick example that I just tested and found to work:

Imports System.Reflection

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim obj As New Test
        Dim objType = obj.GetType()
        Dim method1 = objType.GetMethod("Method1", BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic)
        Dim method2 = objType.GetMethod("Method2", BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic)

        method1.Invoke(obj, Nothing)
        method2.Invoke(obj, Nothing)
    End Sub

End Class


Public Class Test

    Public Sub Method1()
        MessageBox.Show("Public")
    End Sub

    Private Sub Method2()
        MessageBox.Show("Private")
    End Sub

End Class


来源:https://stackoverflow.com/questions/21899293/how-to-invoke-a-non-public-method-through-reflection-without-worrying-about-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!