必须用到反射,加载System.Reflection
Imports System
Imports System.Reflection
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim MyObject As New Form1()
Dim myType As Type = MyObject.GetType()
Dim mi2 As MethodInfo = myType.GetMethod("Test")
mi2.Invoke(Me, New Object() {"TestABC"})
Dim mi3 As MethodInfo = myType.GetMethod("Test2")
mi3.Invoke(Me, New Object() {"ABC"})
Dim str As String = CType(mi3.Invoke(Me, New Object() {"TestABC"}), String)
MessageBox.Show(str)
End Sub
Public Sub Test(ByVal a As String)
MessageBox.Show(a.ToString)
End Sub
Public Function Test2(ByVal a As String) As String
Return a + " Test"
End Function
End Class
执行结果分别为显示 TestABC与ABCTest,实现所需要的功能。
本文展示了如何在C#中利用反射技术来调用类中的特定方法,通过实例化对象并获取其类型,进一步获取并调用方法。实现了两个方法的调用,一个显示字符串,另一个返回字符串与前缀拼接的结果。

被折叠的 条评论
为什么被折叠?



