如何:定义运算符 (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