Public Sub demoSub(Of t)(ByVal arg() As t)
End Sub
Public Sub callDemoSub()
Dim twoDimensions(,) As Integer
demoSub(twoDimensions)
End Sub
您只能透過省略所有型別引數來叫用型別推斷。 如果您提供一個型別引數,就必須提供所有型別引數。
只有泛型程序才支援型別推斷。 您無法在泛型類別、結構、介面或委派上叫用型別推斷。
範例
描述
下列範例定義一個泛型 Function 程序來尋找陣列中的特定元素。 該範例定義一個型別參數,並使用它來建構參數清單中的兩個參數。
程式碼
Public Function findElement(Of T As IComparable) (
ByVal searchArray As T(), ByVal searchValue As T) As Integer
If searchArray.GetLength(0) > 0 Then
For i As Integer = 0 To searchArray.GetUpperBound(0)
If searchArray(i).CompareTo(searchValue) = 0 Then Return i
Next i
End If
Return -1
End Function
註解
上述範例需要能夠將 searchValue 與 searchArray 的每個元素進行比較。 為了確保能夠這樣做,它會限制型別參數 T 來實作 IComparable<T> 介面。 此程式碼使用 CompareTo 方法而非 = 運算子,因為提供給 T 的型別引數不保證支援 = 運算子。
您可以使用下列程式碼測試 findElement 程序。
Public Sub tryFindElement()
Dim stringArray() As String = {"abc", "def", "xyz"}
Dim stringSearch As String = "abc"
Dim integerArray() As Integer = {7, 8, 9}
Dim integerSearch As Integer = 8
Dim dateArray() As Date = {#4/17/1969#, #9/20/1998#, #5/31/2004#}
Dim dateSearch As Date = Microsoft.VisualBasic.DateAndTime.Today
MsgBox(CStr(findElement(Of String)(stringArray, stringSearch)))
MsgBox(CStr(findElement(Of Integer)(integerArray, integerSearch)))
MsgBox(CStr(findElement(Of Date)(dateArray, dateSearch)))
End Sub
Do you want to create custom procedures in AL? This module focuses on explaining how you can create new procedures. Additionally, it describes the difference between local and global procedures, the difference between local and global variables, and how you can pass variables to a procedure.