如何:定義轉換運算子 (Visual Basic)
如果已定義類別或結構,則可定義類別或結構型別與其他資料型別 (例如 Integer、Double 或 String) 之間的型別轉換運算子。
將型別轉換定義成類別或結構內的 CType 函式 (Visual Basic)程序。 所有轉換程序都必須是 Public Shared,且每個程序都必須指定 Widening (Visual Basic) 或 Narrowing (Visual Basic)。
在類別或結構上定義運算子,也稱為「多載」(Overload) 運算子。
範例
下列範例會定義名為 digit 之結構與 Byte 間的轉換運算子。
Public Structure digit
Private dig As Byte
Public Sub New(ByVal b As Byte)
If (b < 0 OrElse b > 9) Then Throw New System.ArgumentException(
"Argument outside range for Byte")
Me.dig = b
End Sub
Public Shared Widening Operator CType(ByVal d As digit) As Byte
Return d.dig
End Operator
Public Shared Narrowing Operator CType(ByVal b As Byte) As digit
Return New digit(b)
End Operator
End Structure
您可以使用下列程式碼來測試結構 digit。
Public Sub consumeDigit()
Dim d1 As New digit(4)
Dim d2 As New digit(7)
Dim d3 As digit = CType(CByte(3), digit)
Dim s As String = "Initial 4 generates " & CStr(CType(d1, Byte)) &
vbCrLf & "Initial 7 generates " & CStr(CType(d2, Byte)) &
vbCrLf & "Converted 3 generates " & CStr(CType(d3, Byte))
Try
Dim d4 As digit
d4 = CType(CType(d1, Byte) + CType(d2, Byte), digit)
Catch e4 As System.Exception
s &= vbCrLf & "4 + 7 generates " & """" & e4.Message & """"
End Try
Try
Dim d5 As digit = CType(CByte(10), digit)
Catch e5 As System.Exception
s &= vbCrLf & "Initial 10 generates " & """" & e5.Message & """"
End Try
MsgBox(s)
End Sub