电脑爱好者,提供IT资讯信息及各类编程知识文章介绍,欢迎大家来本站学习电脑知识。 最近更新 | 联系我们 RSS订阅本站最新文章
电脑爱好者
站内搜索: 
当前位置:首页>> C#>>HOW TO:初始化共享变量:

HOW TO:初始化共享变量

来源:www.cncfan.com | 2006-4-4 | (有2082人读过)

学习----转载

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



C#热门文章排行
网站赞助商
购买此位置

 

关于我们 | 网站地图 | 文档一览 | 友情链接| 联系我们

Copyright © 2003-2024 电脑爱好者 版权所有 备案号:鲁ICP备09059398号