用属性封装 Session 及 VIewState 的存取
Posted on 2008-05-02 19:19 jeff377 阅读(1192) 评论(13) 编辑 收藏 所属分类: ASP.NET
在 ASP.NET 程序中常会 Session 及 VIewState 储存状态,一般的写法都是直接存取 Session 或 ViewState,例如将变量值储存于 Session 的写法如下。
'将变量值储存于 Session 中。2
Dim oValue As New NameValueCollection3
Session(KEY_SESSION) = oValue4

5
'由 Session 中转型取得变量值。6
Dim oValue As NameValueCollection7
oValue = CType(Session(KEY_SESSION), NameValueCollection)8

不过上述的写法有一些缺点:
1.每次存取 Session 时都要做型别转换的动作,执行效能不佳。
2.容易因为 Session 键值错误,而造成不可预期的问题。
3.程序维护上较困难。例如改变键值或 Session 改储存于 ViewState 中。
所以比较好的作法,就是使用属性来封装 Session 或 VIewState 的存取。以下的范例中,使用 SessionCollection 属性来封装 Session 的存取,ViewStateCollection 属性来封装 ViewState 的存取。
Private KEY_SESSION = "_SeesionCollection"2
Private KEY_VIEWSTATE = "_ViewStateCollection"3
Private FSessionCollection As NameValueCollection4
Private FViewStateCollection As NameValueCollection5

6
''' <summary>7
''' 封装 Session 存取的属性。8
''' </summary>9
Private ReadOnly Property SeesionCollection() As NameValueCollection10
Get11
'若区域变量为 Nothing 才重新取得,防止重复做型别转换的动作12
If FSessionCollection Is Nothing Then13
If Session(KEY_SESSION) Is Nothing Then14
FSessionCollection = New NameValueCollection()15
Session(KEY_SESSION) = FSessionCollection16
Else17
FSessionCollection = CType(Session(KEY_SESSION), NameValueCollection)18
End If19
End If20
Return FSessionCollection21
End Get22
End Property23

24
''' <summary>25
''' 封装 ViewState 存取的属性。26
''' </summary>27
''' <value></value>28
Private ReadOnly Property ViewStateCollection() As NameValueCollection29
Get30
'若区域变量为 Nothing 才重新取得,防止重复做型别转换的动作31
If FViewStateCollection Is Nothing Then32
If ViewState(KEY_VIEWSTATE) Is Nothing Then33
FViewStateCollection = New NameValueCollection()34
ViewState(KEY_VIEWSTATE) = FSessionCollection35
Else36
FViewStateCollection = CType(ViewState(KEY_VIEWSTATE), NameValueCollection)37
End If38
End If39
Return FViewStateCollection40
End Get41
End Property42

当要使用封装 Session 及 ViewState 时,就如同存取属性一样。
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click2
Dim iCount As Integer3

4
iCount = Me.SeesionCollection.Count5
Me.SeesionCollection.Add(iCount.ToString, iCount.ToString)6

7
iCount = Me.ViewStateCollection.Count8
Me.ViewStateCollection.Add(iCount.ToString, iCount.ToString)9
End Sub利用属性封装 Session 或 ViewState 的存取时,有下列优点:
1.撰写程序代码时不用去理会 Seesion 或 ViewState,直接使用属性即可,简化程序代码及易读性。
2.只做一次的型别转换,执行效能较佳。
3.程序维护性佳。当 Session 或 ViewState 的键值变更或储存目的改变时(如 Session 改为 ViewState),只需修改该属性即可。
以上的做法虽然以 Session 及 ViewState 做示范,当然也可以使用相同方式来封装 Application 及 Cache 的存取,也可达到上述的优点。
浙公网安备 33010602011771号