VB⼊门(6):类~构造函数,事件
VB中的类的构造函数是
sub New()
end sub
当然,你也可以加参数。⽐如Human类的构造函数:
sub New(Byval Name as string, byval Gender as String, byval Stature as integer)
me.Name = Name          'me是VB中的关键字,表⽰对象⾃⼰,如同java中
me.Gender = Gender      '的this。java中的super在VB中就是MyBase
me.Stature = Stature
end sub
这样,我们的⽼王就是
dim LaoWang As new Human("⽼王", "男", 177)
这样的话,构造Human对象的时候就必须带参数了。我们可以另加⼀个不带参数的New过程。这⾥就略过了。
对象不是死的,是活的。对象应该能够主动向外界做出⼀些表⽰。这就是事件。⽐如⼀个⼈⽣了病。这个时候我们就要把他送到医院去。我们先在Human类当中定义⼀个事件:
writeline函数
public event FallIll
我们假设某⼈暴饮暴⾷,吃出病了。在Eat过程中写上:
public sub Eat()
raiseevent FallIll  'raiseevent⽤来引发⼀个事件
end sub
外界怎样来接收这个事件呢?⽤AddHandler。我们要先定义⼀个过程:
sub GoToHospital
Console.WriteLine("病⼈被送到医院去了。")
end sub
然后将这个过程绑定到⼀个具体的对象的事件上:
AddHandler LaoWang.FallIll, AddressOf GoToHospital
这样,⼀旦执⾏LaoWang.Eat,就会引发FallIll事件,这时GoToHospital过程就会执⾏。完整的代码如下:
imports System
public module MyModule
sub Main
dim LaoWang as Human
LaoWang = new Human("⽼王", "男", 177)
AddHandler LaoWang.FallIll, AddressOf GoToHospital
Console.writeline("{0}, {1},⾝⾼{2}厘⽶", _
LaoWang.Name, LaoWang.Gender, LaoWang.Stature)
LaoWang.Eat()      '这⾥引发事件
Console.Read
end sub
sub GoToHospital
Console.WriteLine("病⼈被送到医院去了。")
end sub
end module
public class Human
public Name as String
public Gender as String
public Stature as integer
sub New(Byval Name as string, byval Gender as String, byval Stature as integer)
me.Name = Name
me.Gender = Gender
me.Stature = Stature
end sub
sub New()    '不带参数的构造函数
end sub
public event FallIll
public sub Eat()
raiseevent FallIll
end sub
public sub Sleep()
end sub
public sub SeeADoctor()
end sub
public function Born() as Human
if Gender = "⼥" then
return new Human("","",50)
else
return nothing
end if
end function
end class
事件还可以带参数。⽐⽅我们把FallIll的定义改为:public event FallIll(Byval Name as String)
然后把Eat的内容改为:
raiseevent FallIll(me.Name)
接着把GoToHospital的定义改为:
sub GoToHospital(Byval Name as String)
Console.WriteLine(Name & "被送到医院去了。") end sub
这时候运⾏我们就会看到:“⽼王被送到医院去了。”