HOW TO:定義運算子 (Visual Basic)
若已定義類別或結構,則當其中一或兩個運算元的型別是類別或結構的型別時,就可以定義標準運算子的行為 (例如 *、<> 或 And)。
將標準運算子定義成類別或結構內部的運算子程序。所有運算子程序都必須是 PublicShared。
在類別或結構上定義運算子,也稱為「多載」(Overload) 運算子。
範例
下列範例定義 height 結構的 + 運算子。結構使用以英呎和英吋測量的高度。一「英吋」(Inch) 是 2.54 公分,一「英呎」(Foot) 則是 12 英吋。為了確保值標準化 (英吋 < 12.0),建構函式會執行 modulo 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
如需詳細資訊和範例,請參閱 Visual Basic 2005 中的運算子多載 (英文)。
請參閱
工作
HOW TO:使用定義運算子的類別 (Visual Basic)