如何通过反射调用非公共方法而不必担心方法的可见性? [英] How to invoke a non-public method through Reflection without worrying about the method visibility?
问题描述
我只是出于好奇而测试反射事物,并且尝试调用私有方法,但由于是Private
,所以我找不到它.
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
.
但是我真正想知道的是,是否可以在反射搜索中自动检索该方法的可见性,而不用担心调用的方法是私有的,共享的,朋友的,公共的等等.有一个BindingFlags
标志组合可以无差别地调用方法,其中方法可见性是什么?我的意思是不必担心方法可见性.
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.
这是我的代码:
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
推荐答案
BindingFlags
值Public
和NonPublic
并不互斥.每个成员仅表示具有该访问级别的成员将包括在搜索中.如果要在搜索中同时包含公共成员和非公共成员,则只需同时包含BindingFlags
值.
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
这篇关于如何通过反射调用非公共方法而不必担心方法的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!