1. 程式人生 > >VB 函式 CallByName 的一些用法 (函式動態呼叫,回撥函式)

VB 函式 CallByName 的一些用法 (函式動態呼叫,回撥函式)

VB  函式  CallByName (函式動態呼叫,回撥函式) 的一些用法

  最近程式設計,要用到函式指標來動態地呼叫函式,在C 語言裡很容易實現,用函式指標就行了。

  VB裡就沒有這麼方便了,查閱相關資料,講起來均很複雜,也不容易明白,其中採用CallByName (函式動態呼叫,回撥函式)是最方便的方法。

  將之歸納為幾個例子,應用方法就一目瞭然了。

Private Sub Command2_Click()
    Dim Args(1) As String

    Args(0) = "0a"
    Args(1) = "1b"
    
    CallByName Me, "SubBy1", VbMethod, "00aa", "11bb"
    Form1.Label1 = (CallByName(Me, "FunBy2", VbMethod, Args(0), Args(1)))
 
    CallByName Text1, "Text", VbLet, "New Text"            '設定屬性
    Text1.Text = " rst=" + CallByName(Text1, "Text", VbGet)  '讀屬性
    CallByName Text1, "Move", VbMethod, 100, 100, 2000, 500    'move方法
End Sub
Sub SubBy1(s1 As String, s2 As String)
    Debug.Print s1 + "  Sub1  " + s2
End Sub
Function FunBy2(s1 As String, s2 As String) As String
    FunBy2 = "Test2 :  " + s1 + " Fun 2 " + s2
End Function

附:

Visual Basic 語言參考


CallByName 函式

執行物件的方法,或者設定或返回物件的屬性

Public Function CallByName( _
   ByVal ObjectRef As System.Object, _
   ByVal ProcName As String, _
   ByVal UseCallType As CallType, _
   ByVal Args() As Object _
) As Object
引數
ObjectRef
必選。Object。指向公開屬性或方法的物件的指標。

ProcName
必選。String。包含物件的屬性名或方法名的字元

串表示式。

UseCallType
必選。CallType 列舉型別的列舉成員,表示所呼叫過程的型別。CallType 的值可以是 Method、Get 或 Set。

Args
可選。ParamArray。引數陣列,包含要傳遞給所呼叫的屬性和方法的引數。