HOW TO:定義轉換運算子 (Visual Basic)How to: Define a Conversion Operator (Visual Basic)

如果您已定義類別或結構,您可以定義您自己的類別或結構的類型與另一個資料類型之間的型別轉換運算子 (例如IntegerDouble,或String)。If you have defined a class or structure, you can define a type conversion operator between the type of your class or structure and another data type (such as Integer, Double, or String).

定義類型轉換成CType 函式類別或結構內的程序。Define the type conversion as a CType Function procedure within the class or structure. 所有的轉換程序必須是Public Shared,以及每一個都必須指定Widening或是NarrowingAll conversion procedures must be Public Shared, and each one must specify either Widening or Narrowing.

類別或結構上定義的運算子,也稱為多載運算子。Defining an operator on a class or structure is also called overloading the operator.


下列範例會定義結構,稱為之間的轉換運算子digitByteThe following example defines conversion operators between a structure called digit and a 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為下列程式碼。You can test the structure digit with the following code.

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))
        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
        Dim d5 As digit = CType(CByte(10), digit)
    Catch e5 As System.Exception
        s &= vbCrLf & "Initial 10 generates " & """" & e5.Message & """"
    End Try
End Sub

另請參閱See also