HOW TO:定義運算子 (Visual Basic)How to: Define an Operator (Visual Basic)

如果您已定義類別或結構,您可以定義標準運算式的行為 (例如*<>,或And) 當一或兩個運算元屬於您自己的類別或結構的類型。If you have defined a class or structure, you can define the behavior of a standard operator (such as *, <>, or And) when one or both of the operands is of the type of your class or structure.

標準的運算子定義為類別或結構中的運算子程序。Define the standard operator as an operator procedure within the class or structure. 必須是所有的運算子程序Public SharedAll operator procedures must be Public Shared.

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

範例Example

下列範例會定義+結構的運算子稱為heightThe following example defines the + operator for a structure called height. 結構會使用以英呎和英吋為單位的高度。The structure uses heights measured in feet and inches. 英吋是 2.54 公分為單位,而另一個步行12 英吋。One inch is 2.54 centimeters, and one foot is 12 inches. 若要確保正規化的值 (英吋為單位 < 12.0),建構函式會執行模數12 算術。To ensure normalized values (inches < 12.0), the constructor performs modulo 12 arithmetic. +運算子使用建構函式來產生正規化的值。The + operator uses the constructor to generate normalized values.

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為下列程式碼。You can test the structure height with the following code.

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

另請參閱See also