技巧vb.net中的操作符應用實例

發表于:2008-04-10來源:作者:點擊數: 標簽:
任何一門語言都提供了豐富的操作符, vb 也不例外。操作符一般分為:算術運算符,賦值運算符,比較運算符,邏輯運算符,其它。本文只以幾個小例子來介紹其中一些比較重要的應用。 在本文中將會用到一個自定義類 dog ,代碼如下: Public Class dogClass dog P
任何一門語言都提供了豐富的操作符,vb也不例外。操作符一般分為:算術運算符,賦值運算符,比較運算符,邏輯運算符,其它。本文只以幾個小例子來介紹其中一些比較重要的應用。

  在本文中將會用到一個自定義類 dog ,代碼如下:


Public Class dogClass dog
Private s_name As String
Private s_color As Color
Private s_age As Integer
Public Sub New()Sub New()
s_name = "塞北的雪"
s_age = 22
s_color = System.Drawing.Color.Red
End Sub
Public Property Name()Property Name() As String
Get
Return s_name
End Get
Set(ByVal value As String)
s_name = value
End Set
End Property
Public Property Color()Property Color() As Color
Get
Return s_color
End Get
Set(ByVal value As Color)
s_color = value
End Set
End Property
Public Property Age()Property Age() As Integer
Get
Return s_age
End Get
Set(ByVal value As Integer)
s_age = value
End Set
End Property
Public Shared Operator +(ByVal a As dog, ByVal b As dog)
Dim c As New dog
c.Name = a.Name + b.Name
c.Age = a.Age + b.Age
c.Color = Color.FromArgb((a.Color.ToArgb + b.Color.ToArgb) / 2)
Return c
End Operator

End Class

  1,Is 運算符

  Is運算符比較兩個引用對象是否引用了同一實例。 例子如下:

Dim a As New dog
Dim b As New dog()
If a Is b Then
MsgBox("True")
Else
MsgBox("False")
End If
b = a
b.Name = "NorthSnow"


If a Is b Then
MsgBox("True")
Else
MsgBox("false")
End If
'false
'true

  2,操作符重載

  我們可以根據需要對操作符進行重載,本文中的 dog 類 就 對 + 操作符 進行了重載 操作。此時對兩個dog 類進行相加時,會返回一個dog 類實例 ,他的 Name 是 那兩個 dog 實例的 名字相加,年齡也是 dog 實例的年齡之和,顏色是兩個顏色的平均值。例子如下:


Dim sb As New System.Text.StringBuilder
Dim m As New dog
Dim n As New dog
Dim c As dog
m.Name = "NorthSnow"
c = m + n

sb.AppendLine()
sb.Append(m.Name)
sb.Append("--")
sb.Append(m.Age)
sb.Append("--")
sb.Append(m.Color.ToArgb)

sb.AppendLine()
sb.Append(n.Name)
sb.Append("--")
sb.Append(n.Age)
sb.Append("--")
sb.Append(n.Color.ToArgb)

sb.AppendLine()
sb.Append(c.Name)
sb.Append("--")
sb.Append(c.Age)
sb.Append("--")
sb.Append(c.Color.ToArgb)
MsgBox(sb.ToString)

'NorthSnow--22---65536
'塞北的雪--22---65536
'NorthSnow塞北的雪--44---65536

原文轉自:http://www.anti-gravitydesign.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97