溫馨提示×

VB中泛型編程是怎么實(shí)現(xiàn)的

vb
小億
87
2024-04-03 15:31:58
欄目: 編程語言

在VB中,泛型編程可以通過定義泛型類、泛型接口和泛型方法來實(shí)現(xiàn)。

  1. 定義泛型類:在類的聲明前面加上Of關(guān)鍵字和類型參數(shù)列表來定義泛型類。例如:
Public Class GenericClass(Of T)
    Private _value As T

    Public Sub New(value As T)
        _value = value
    End Sub

    Public Function GetValue() As T
        Return _value
    End Function
End Class
  1. 定義泛型接口:在接口的聲明前面加上Of關(guān)鍵字和類型參數(shù)列表來定義泛型接口。例如:
Public Interface IGenericInterface(Of T)
    Function GetValue() As T
End Interface
  1. 定義泛型方法:在方法的聲明前面加上Of關(guān)鍵字和類型參數(shù)列表來定義泛型方法。例如:
Public Sub PrintValue(Of T)(value As T)
    Console.WriteLine(value)
End Sub

使用泛型類、泛型接口和泛型方法時,可以通過指定具體的類型參數(shù)來實(shí)例化類、實(shí)現(xiàn)接口或調(diào)用方法,例如:

Dim intClass As New GenericClass(Of Integer)(10)
Console.WriteLine(intClass.GetValue())

Dim strClass As New GenericClass(Of String)("Hello")
Console.WriteLine(strClass.GetValue())

Dim intList As New List(Of Integer)()
intList.Add(1)
intList.Add(2)

Dim doubleList As New List(Of Double)()
doubleList.Add(1.5)
doubleList.Add(2.5)

Dim genericList As New List(Of T)()
genericList.AddRange(intList)
genericList.AddRange(doubleList)

0