而不是做
session("myvar1") = something session("myvar2") = something session("myvar3") = something session("myvar4") = something
是在做
enum sessionVar myvar1 myvar2 myvar3 myvar4 end enum session(sessionVar.myvar1.tostring) = something session(sessionVar.myvar2.tostring) = something session(sessionVar.myvar3.tostring) = something session(sessionVar.myvar4.tostring) = something
会更好?
解决方法
而不是使用会话密钥的常量,我使用我自己的类型安全的会话对象,看起来像这样(对不起,这是在C#,见下面的VB版本):
public class MySession { // Private constructor (use MySession.Current to access the current instance). private MySession() {} // Gets the current session. public static MySession Current { get { MySession session = HttpContext.Current.Session["__MySession__"] as MySession; if (session == null) { session = new MySession(); HttpContext.Current.Session["__MySession__"] = session; } return session; } } // My session data goes here: public string MyString { get; set; }; public bool MyFlag { get; set; }; public int MyNumber { get; set; }; }
每当我需要读/写会话时,我可以使用我的类型安全会话对象,如下所示:
string s = MySession.Current.MyString; s = "new value"; MySession.Current.MyString = s;
这个解决方案有几个优点:
>我有一个类型安全的会话(没有更多的类型转换)
>我可以记录所有基于会话的数据(通过在MySession中注释公共属性)
>当向会话添加新元素时,我不必搜索解决方案来检查是否已经在其他地方使用了同一个会话密钥.
更新:
这是一个VB版本(从C#版本自动转换).对不起,但我不知道VB,所以我不知道如何在VB中写属性:
Public Class MySession ' Private constructor (use MySession.Current to access the current instance). Private Sub New() End Sub ' Gets the current session. Public Shared ReadOnly Property Current() As MySession Get Dim session As MySession = TryCast(HttpContext.Current.Session("__MySession__"),MySession) If session = Nothing Then session = New MySession() HttpContext.Current.Session("__MySession__") = session End If Return session End Get End Property ' My session data goes here: Public MyString As String Public MyFlag As Boolean Public MyNumber As Integer End Class