好了,到這裡,你不想看看完整的例子嗎?這裡重新寫了一個Human類,當中有一個Age(年齡)屬性。我們看看它是怎樣阻止把一個人的年齡設為負值的:
imports System
public module MyModule
sub Main
dim LaoWang as new Human
LaoWang.Name = "老王"
LaoWang.Age = 52
LaoWang.Age = 330 '這句話有沒有把老王的年齡設為330歲呢?看看下一句的結果就知道了。
Console.WriteLine("{0}現在{1}歲。", LaoWang.Name, LaoWang.Age)
Console.ReadLine()
end sub
end module
public class Human
public Name as String
dim mvarAge as integer '這裡沒有指明是public還是private,因為缺省狀態是private
public property Age() as integer
Get
return mvarAge
end Get
Set(Byval Value as integer)
if Value<=0 or Value>=200 then '通常年齡不應該小於1或大於200
Console.WriteLine(Value & "歲?我死了嗎?")
else
mvarAge = value
end if
end set
end property
end class
到這裡你應該閉目養神一會兒:原來屬性是這樣子的啊!
但是話題還沒有完。
比如說,如果成員是一個數組,我該怎樣為它建立屬性呢?為當中的每一個元素建立嗎?那數組大小變化了怎麼辦?Property才不會這麼蠢。我們舉個例子。比方我們給Human類添加一個數組成員Children,表示一個人有多少個孩子。我們先定義mvarChildren:
dim mvarChildren() as Human
為其建立屬性有兩種方式。一種是直接將屬性的類型設為數組:
public property Children() as Human()
Get
return mvarChildren
end Get
Set(Byval Value as Human())
mvarChildren = value
end Set
end property
那麼我們就可以像使用數組一樣來使用這個屬性了。
另一種是在讀取屬性的時候傳入參數index:
Public Property Children(ByVal index As Integer) As Human
Get
Return mvarChildren(index)
End Get
Set(ByVal Value As Human)
mvarChildren(index) = Value
End Set
End Property
這樣可以對傳入的下標進行檢查。
這裡提到讀取屬性的時候可以給參數。這是很有趣的一個東西。比如老王有3個小孩,其中一個叫「王華」。我想根據名字來得到這個小孩,我可以寫一個函數
public function GetChildByName(Byval Name as string) as Human '內容省略了
然後調用
LaoWang.GetChildByName("王華")
就可以了。
要寫成屬性的話,我們可以這樣寫:
public property Child(byval Name as string) as Human
Get
return getChildByName(Name)
end get
set(byval Value as Human)
getChildByName(Name) = Value
end Set
end property