共用方式為


如何:定義運算子 (Visual Basic)

定義類別或結構後,如果一或兩個運算元是類別或結構的類型,您可以定義標準運算子的行為 (例如 *<>And)。

定義標準運算子為類別或結構中的運算子程序。 所有運算子程序都必須是 Public Shared

在類別或結構上定義運算子也稱為多載運算子。

範例

下列範例會針對名為 height 的結構定義 + 運算子。 結構使用以英尺和英寸為單位的高度。 一英寸是 2.54 公分,而一英尺是 12 英寸。 為確保標準化值 (英寸 < 12.0),建構函式會執行模數 12 算術。 + 運算子使用建構函式產生標準化值。

Public Shadows Structure height
    ' Need Shadows because System.Windows.Forms.Form also defines property Height.
    Private feet As Integer
    Private inches As Double
    Public Sub New(ByVal f As Integer, ByVal i As Double)
        Me.feet = f + (CInt(i) \ 12)
        Me.inches = i Mod 12.0
    End Sub
    Public Overloads Function ToString() As String
        Return Me.feet & "' " & Me.inches & """"
    End Function
    Public Shared Operator +(ByVal h1 As height, 
                             ByVal h2 As height) As height
        Return New height(h1.feet + h2.feet, h1.inches + h2.inches)
    End Operator
End Structure

您可以使用下列程式碼來測試結構 height

Public Sub consumeHeight()
    Dim p1 As New height(3, 10)
    Dim p2 As New height(4, 8)
    Dim p3 As height = p1 + p2
    Dim s As String = p1.ToString() & " + " & p2.ToString() &
          " = " & p3.ToString() & " (= 8' 6"" ?)"
    Dim p4 As New height(2, 14)
    s &= vbCrLf & "2' 14"" = " & p4.ToString() & " (= 3' 2"" ?)"
    Dim p5 As New height(4, 24)
    s &= vbCrLf & "4' 24"" = " & p5.ToString() & " (= 6' 0"" ?)"
    MsgBox(s)
End Sub

另請參閱