Porady: definiowanie operatora (Visual Basic)

Jeśli zdefiniowano klasy lub strukturamożna zdefiniować zachowanie standardowego operator (takie jak *, <>, lub And) kiedy jest jeden lub oba operandy typu klasy lub struktura.

Można zdefiniować standardowe operator operator procedura , w ramach klasy lub struktura.Wszystkie procedury operator musi być PublicShared. 

Definiowanie operator na klasy lub struktura jest również nazywany przeciążanie operator.

Przykład

Poniższy przykład definiuje +o nazwie operator dla struktura height. struktura używa wysokości mierzone w stopy i cale.Jeden cala jest 2,54 cm i jednego podnośnika jest 12 cali.Aby zapewnić wartości znormalizowanych (cale < wykonuje konstruktor 12.0), modulo 12 arytmetycznych.+ operator używa konstruktor , aby wygenerować znormalizowanej 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żna przetestować struktura height z 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

Aby uzyskać dodatkowe informacje i przykłady, zobacz Przeciążanie operatora, w Visual Basic 2005.

Zobacz też

Zadania

Porady: definiowanie operatora konwersji (Visual Basic)

Porady: wywoływanie procedury operatora (Visual Basic)

Porady: używanie klasy definiującej operatory (Visual Basic)

Porady: deklarowanie struktury (Visual Basic)

Informacje

Operator — Instrukcja

Structure — Instrukcja

Mod — Operator (Visual Basic)

Koncepcje

Procedury operatorów (Visual Basic)