Porady: definiowanie operatora (Visual Basic)

Jeśli zdefiniowano klasę lub strukturę, można zdefiniować zachowanie operatora standardowego (takiego jak *, <>lub ), gdy jeden lub Andoba operandy mają typ klasy lub struktury.

Zdefiniuj operator standardowy jako procedurę operatora w klasie lub strukturze. Wszystkie procedury operatora muszą mieć wartość PublicShared.

Definiowanie operatora w klasie lub strukturze jest również nazywane przeciążeniem operatora.

Przykład

W poniższym przykładzie zdefiniowano + operator struktury o nazwie height. Struktura używa wysokości mierzonych w stopach i calach. Jeden cal ma 2,54 centymetra, a jedna stopa ma 12 cali. Aby zapewnić znormalizowane wartości (w calach < 12.0), konstruktor wykonuje modulo 12 arytmetyczny. Operator + używa konstruktora do generowania znormalizowanych wartości.

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

Możesz przetestować strukturę height przy użyciu następującego kodu.

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

Zobacz też