How to invoke a non-public method through Reflecti

2019-08-08 19:23发布

问题:

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