Reflection果然很嚣张

即使一个Class的Constructor是Private的,也可以通过如下方式构造之:
Activator.CreateInstance(GetType(Class1), True)
即使是Private的Method也可以随意调用之:
Private Function GetMethod(ByVal ObjectType As Type, _
                                  ByVal Method As String) As Reflection.MethodInfo
        Return ObjectType.GetMethod(Method, FlattenHierarchy Or _
                                            Instance Or _
                                            System.Reflection.BindingFlags.Public Or _
                                            NonPublic)
End Function
下面给个完整的测试例子:
一个简单的测试Class:
Public Class Class1
    Private lsTestStr As String = Nothing
    Private Sub New()
        lsTestStr = "Hello"
    End Sub
    Private Function SayHello() As String
        Return lsTestStr
    End Function
End Class
一个简单的winform:
Imports System.Reflection.BindingFlags
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim loObj As Object = Activator.CreateInstance(GetType(Class1), True)
        MsgBox(CallMethod(loObj, "SayHello", Nothing))
 
    End Sub

    Private Function GetMethod(ByVal ObjectType As Type, _
                                  ByVal Method As String) As Reflection.MethodInfo
        Return ObjectType.GetMethod(Method, FlattenHierarchy Or _
                                            Instance Or _
                                            System.Reflection.BindingFlags.Public Or _
                                            NonPublic)
    End Function
    Private Function CallMethod(ByVal obj As Object, _
                                 ByVal method As String, _
                                 ByVal ParamArray params() As Object) As Object
        Dim info As Reflection.MethodInfo = GetMethod(obj.GetType, method)
        Dim result As Object
        Try
            result = info.Invoke(obj, params)
        Catch e As Exception
            Throw e.GetBaseException
        End Try
        Return result
    End Function

End Class


 

你可能感兴趣的:(class,function,object,string,winform,constructor)