假设我已经实例化了这样一个对象:
Dim PerformPageSize as New HtmlToRtf.CPageStyle.CPageSize()
Object包含一些方法成员,我把它放在这样的Enumeration中,我的意思是,枚举字符串与方法名称相同:
Friend Enum PageSize
Auto
A3
A4
A5
A6
Folio
Letter
Statement
End Enum
我将Enum作为参数传递给方法:
Friend Sub Test(Byval _pagesize as PageSize)
End Sub
好吧,现在我的意图(避免写一个大的Select case并高效地执行此操作)是解析Enum值名称以调用方法(它具有完全相同的名称)
所以我想简化一下:
Friend Sub Test(Byval _pagesize as PageSize)
Dim PerformPageSize As New HtmlToRtf.CPageStyle.CPageSize()
Select Case PageSize
Case PageSize.Auto
PerformPageSize.Auto()
Case PageSize.A3
PerformPageSize.A3()
Case PageSize.A4
PerformPageSize.A4()
Case PageSize.A5
PerformPageSize.A5()
' Etc...
End Select
End Sub
进入类似的事情:
(我知道这段代码没有任何意义,但只是为了理解这个想法,因为我不知道如何使用反射或其他任何东西成为真正的解决方案):
Friend Sub Test(Byval _pagesize as PageSize)
Dim PerformPageSize As New HtmlToRtf.CPageStyle.CPageSize()
' Parse the Enum value as the Method from the object
Dim Method = PerformPageSize.TryPase(GetType(PageSize), _pagesize).ToString
' Call the equivalent method
PerformPageSize.[Method]()
End Sub
答案 0 :(得分:4)
你可以使用这样的反射:
Friend Sub Test(Byval _pagesize as PageSize)
Dim performPageSize As New HtmlToRtf.CPageStyle.CPageSize()
Dim pageType As Type = performPageSize.GetType()
Dim method As MethodInfo = pageType.GetMethod(_pagesize.ToString())
If Not method Is Nothing Then
method.Invoke(performPageSize, Nothing)
End If
End Sub
只要方法是公开的,这就应该有效。如果没有,您需要使用第二个参数帮助GetMethod()
方法来指定方法的可见性。