HOW TO:初始化共享变量
“初始化共享变量”本不是一个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