在 ASP.NET 程序中常会 Session 及 VIewState 储存状态,一般的写法都是直接存取 Session 或 ViewState,例如将变量值储存于 Session 的写法如下。
'将变量值储存于 Session 中。
Dim oValue As New NameValueCollection
Session(KEY_SESSION) = oValue
'由 Session 中转型取得变量值。
Dim oValue As NameValueCollection
oValue = CType(Session(KEY_SESSION), NameValueCollection)
不过上述的写法有一些缺点:
1.每次存取 Session 时都要做型别转换的动作,执行效能不佳。
2.容易因为 Session 键值错误,而造成不可预期的问题。
3.程序维护上较困难。例如改变键值或 Session 改储存于 ViewState 中。
所以比较好的作法,就是使用属性来封装 Session 或 VIewState 的存取。以下的范例中,使用 SessionCollection 属性来封装 Session 的存取,ViewStateCollection 属性来封装 ViewState 的存取。
Private KEY_SESSION = "_SeesionCollection"
Private KEY_VIEWSTATE = "_ViewStateCollection"
Private FSessionCollection As NameValueCollection
Private FViewStateCollection As NameValueCollection
''' <summary>
''' 封装 Session 存取的属性。
''' </summary>
Private ReadOnly Property SeesionCollection() As NameValueCollection
Get
'若区域变量为 Nothing 才重新取得,防止重复做型别转换的动作
If FSessionCollection Is Nothing Then
If Session(KEY_SESSION) Is Nothing Then
FSessionCollection = New NameValueCollection()
Session(KEY_SESSION) = FSessionCollection
Else
FSessionCollection = CType(Session(KEY_SESSION), NameValueCollection)
End If
End If
Return FSessionCollection
End Get
End Property
''' <summary>
''' 封装 ViewState 存取的属性。
''' </summary>
''' <value></value>
Private ReadOnly Property ViewStateCollection() As NameValueCollection
Get
'若区域变量为 Nothing 才重新取得,防止重复做型别转换的动作
If FViewStateCollection Is Nothing Then
If ViewState(KEY_VIEWSTATE) Is Nothing Then
FViewStateCollection = New NameValueCollection()
ViewState(KEY_VIEWSTATE) = FSessionCollection
Else
FViewStateCollection = CType(ViewState(KEY_VIEWSTATE), NameValueCollection)
End If
End If
Return FViewStateCollection
End Get
End Property
当要使用封装 Session 及 ViewState 时,就如同存取属性一样。
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim iCount As Integer
iCount = Me.SeesionCollection.Count
Me.SeesionCollection.Add(iCount.ToString, iCount.ToString)
iCount = Me.ViewStateCollection.Count
Me.ViewStateCollection.Add(iCount.ToString, iCount.ToString)
End Sub利用属性封装 Session 或 ViewState 的存取时,有下列优点:
1.撰写程序代码时不用去理会 Seesion 或 ViewState,直接使用属性即可,简化程序代码及易读性。
2.只做一次的型别转换,执行效能较佳。
3.程序维护性佳。当 Session 或 ViewState 的键值变更或储存目的改变时(如 Session 改为 ViewState),只需修改该属性即可。
以上的做法虽然以 Session 及 ViewState 做示范,当然也可以使用相同方式来封装 Application 及 Cache 的存取,也可达到上述的优点。