“初始化共享变量”本不是一个how to问题。这里提出来,主要的再次认识一下new。
在创建构造函数时,new是很有趣的,sub new()有别于别的函数,因为它可以出现两次。
public class testclass
shared sub new()
…
end sub
sub new()
…
end sub
…
end class
当 dim t as new testclass时,它先执行shared sub new()然后再执行sub new()。shared sub new()只执行一次,在实例类中,它在第一个实例产生时执行。
运用这个特性,shared sub new()在初始化类的共享变量时就会特别的方便。
下面作一个比较:
在静态类中,
public class mycommand 使用shared sub new()
private shared cn as sqlclient.sqlconnection
shared sub new()
cn = new sqlclient.sqlconnection(“persist security info=false;integrated security=sspi;database=northwind;server=(local)”)
end sub
public shared function command(byval commandtext as string) as sqlclient.sqlcommand
return new sqlclient.sqlcommand(commandtext, cn)
end function
end class
public class mycommand0 不使用shared sub new()
private shared cn as sqlclient.sqlconnection
public shared function command(byval commandtext as string) as sqlclient.sqlcommand
if cn is nothing then
cn = new sqlclient.sqlconnection(“persist security info=false;integrated security=sspi;database=northwind;server=(local)”)
end if
return new sqlclient.sqlcommand(commandtext, cn)
end function
end class
在实例类中,
public class mycommand1 使用shared sub new()
private shared cn as sqlclient.sqlconnection
private _command as sqlclient.sqlcommand
shared sub new()
cn = new sqlclient.sqlconnection(“persist security info=false;integrated security=sspi;database=northwind;server=(local)”)
end sub
sub new()
_command = new sqlclient.sqlcommand(“select * from orders”, cn)
end sub
sub new(byval commandtext as string)
_command = new sqlclient.sqlcommand(commandtext, cn)
end sub
public readonly property command() as sqlclient.sqlcommand
get
return _command
end get
end property
以下省略……
end class
public class mycommand2 不使用shared sub new()
private shared cn as sqlclient.sqlconnection
private _command as sqlclient.sqlcommand
sub new()
if cn is nothing then
cn = new sqlclient.sqlconnection(“persist security info=false;integrated security=sspi;database=northwind;server=(local)”)
end if
_command = new sqlclient.sqlcommand(“select * from orders”, cn)
end sub
sub new(byval commandtext as string)
if cn is nothing then
cn = new sqlclient.sqlconnection(“ersist security info=false;integrated security=sspi;database=northwind;server=(local)”)
end if
_command = new sqlclient.sqlcommand(commandtext, cn)
end sub
public readonly property command() as sqlclient.sqlcommand
get
return _command
end get
end property
以下省略……
end class