它是创建会话值的键名枚举一个好主意? [英] is it a good idea to create an enum for the key names of session values?

查看:126
本文介绍了它是创建会话值的键名枚举一个好主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

而不是做

 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

会更好?

推荐答案

,见下面一个VB版):

Instead of using constants for the session keys, I'm using my own type-safe session object, which looks like this (sorry this is in C#, see below for a VB version):

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; };
}

每当我需要读/写的东西/从会话,我可以用我的类型安全的会话对象是这样的:

Whenever I need to read/write something to/from the session, I can use my typesafe session object like this:

string s = MySession.Current.MyString;
s = "new value";
MySession.Current.MyString = s;

这个解决方案带来了几大优势:

This solution results in several advantages:


  • 我有一个类型安全的会话(没有更多的类型强制转换)

  • 我可以记录所有基于会话的数据(在MySession的评论的公共属性)

  • 添加新元素到会话,我没有搜索解决方案,以检查是否在同一会话密钥已经被用到别的地方。

更新:
这里是一个VB版本(从C#版本自动转换)。很抱歉,但我不知道VB,所以我不知道怎么写的属性在VB:

Update: Here's a VB version (automatically converted from the C# version). Sorry, but I don't know VB and so I didn't know how to write the properties in 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

这篇关于它是创建会话值的键名枚举一个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆