vb.net对运算符的重载
对象的+,-,X,等运算并没有定义,怎么办,可利用现有的运算符,通过重载的方法,实例类似基本类型的运算方式。
运算符重载,用Operator来指明,且必须用Shared进行限定。(类似于C++的友元重载)
而且VB.net的运算符重载很怪,很多运算符必须成对出现重载,否则出错。
比如:=和<>,>和<等必须成对出现重载:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim a As Person = New Person(3)
Dim b As Person = New Person(4)
a = a + 3
TextBox1.Text = a.show()
End Sub
End Class
Public Class Person
Private b As Int32
Public Sub New(Optional d As Int32 = 0)
b = d
End Sub
Public Shared Operator +(ByVal f As Person, ByVal d As Int32) As Person
f.b = f.b + d
Return f
End Operator
Public Shared Operator =(ByVal c As Person, ByVal d As Person) As Boolean
Return c.b = d.b
End Operator
'Public Shared Operator >(ByVal c As Person, ByVal d As Person) As Boolean
' Return c.b > d.b
'End Operator
'Public Shared Operator <(ByVal c As Person, ByVal d As Person) As Boolean
' Return c.b < d.b
'End Operator
Public Shared Operator <>(ByVal c As Person, ByVal d As Person) As Boolean
Return c.b <> d.b
End Operator
Public Function show() As Int32
Return b
End Function
End Class