而不是做

 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

其他提示

只有当这些值是相关的。否则,使用普通的旧的常量。

如何: -

public static class  SessionVar
{
  public static readonly string myVar1 = "myVar1";
  public static readonly string myVar2 = "myVar2";
  public static readonly string myVar3 = "myVar3";
  public static readonly string myVar4 = "myVar4";
}

这允许您使用: -

session(SessionVar.myVar1) = something;

我用类这样做一个类型的会话/缓存包装。您可能需要额外的代码添加到了get / set,但我会离开,你。

internal class SessionHelper
{
    private const string  myVar1Key = "myvar1";

    public static int MyVar1
    {
        get
        {
            return (int)System.Web.HttpContext.Current.Session[myVar1Key];
        }
        set
        {
            System.Web.HttpContext.Current.Session[myVar1Key] = value;
        }
    }
}

很抱歉的C#....

有关删除所有字符串键引用的简单的事情,我会去与全局静态/共享的应用范围可见常量。

有关会话变量,否则,强类型的简单的包装是一个更好的选择,并且它更OOP友好的考虑,你得到IntelliSense和对象浏览器的兼容性。

我可以看到多值的枚举存在的唯一方法是将被用于索引到阵列或类似的列表。但即使如此,你必须枚举转换为int。

所以,你可以有你在应用程序启动时加载的所有会话变量的键,然后枚举的索引数组。然而,考虑到Session对象从HttpSessionState,它自IEnumerable派生派生,你应该能够只是做一个foreach循环在会话变量,如果您需要。

我意识到这个问题,有人问前一阵子和“答案”已经被摘下。但我只是碰到它。马丁的回答是好。然而,为了有助于谁在未来过这个失蹄,如果你真的想要一个漂亮的方式来处理会话,阅读的帖子。我不认为你会发现任何东西更容易。

我想出了张贴避免通过保持Session变量的结构不变的其他解决方案的某些缺点的解决方案。这是一个简单的类型安全快捷获取和设置会话变量。

这是C#,但我贴一些自动生成VB.NET在末端。

我见过的最好的解决方案(公认的答案和一个由TheObjectGuy)要求存储在一个会话变量,然后从会话拉的东西,如MySessionClass.Current.MyProperty来访问它的属性自定义类。

这样做的问题是,如果你正在使用(或将来可能使用),比一个inproc会话状态模式以外的东西(见的 https://msdn.microsoft.com/en-us/library/ms178586%28v=vs.140%29.aspx ),整个类将要经过串行化来访问的一个属性。

此外,这意味着你失去了通过实际会话提供的IEnumerable和集合接口的实现,如果你需要的。我的解决方案,你可以,如果你需要这个功能,只需要访问实际的会话。

您可以轻松地使用这些会话变量,他们是类型安全的。它可以沿着如会话[“myProperty的”]语句,这将允许在一时间的现有项目一个参考的转换中使用。所以:

int myInt = (int)Session["MyInt"];
Session["MyInt"] = 3;

变为:

int myInt = SessionVars.MyInt; 
SessionVars.MyInt = 3;

下面是实际的类。该CallerMemberName需要.NET 4.5,但即使你使用的是旧版本,你仍然可以被明确传递propertyName的管理。此外,类型的属性必须是可空的,使之作用完全一样的标准会话[“MyProp”]调用因为非设置

public static class SessionVars
{
    private static T Get2<T>([System.Runtime.CompilerServices.CallerMemberName] string propertyName = "") 
    {
        if (HttpContext.Current.Session[propertyName] == null)
        {
            return default(T);
        }

        return (T)HttpContext.Current.Session[propertyName];
    }

    private static void Set2<T>(T value, [System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
    {
        HttpContext.Current.Session[propertyName] = value;
    }

    public static int MyInt { get { return Get2<int>(); } set { Set2<int>(value); } }
    public static bool MyBool { get { return Get2<bool>(); } set { Set2<bool>(value); } }
    public static string MyString { get { return Get2<string>(); } set { Set2<string>(value); } }
}

我甚至写了一个代码段,以方便添加这些属性:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>SessionVars Property</Title>
    <Author>kevinpo</Author>
    <Shortcut>sv</Shortcut>
    <Description>Adds a property for use in a SessionVars class</Description>
    <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>type</ID>
        <Default>int</Default>
      </Literal>
      <Literal>
        <ID>property</ID>
        <Default>PropertyName</Default>
      </Literal>
    </Declarations>
    <Code Language="CSharp">
      <![CDATA[public static $type$ $property$ { get { return Get2<$type$>(); } set { Set2<$type$>(value); } }]]>
    </Code>
  </Snippet>
</CodeSnippet>

我是C#的人,所以这VB.NET只是自动换算通过 HTTP://converter.telerik的.com /

Public NotInheritable Class SessionVars
    Private Sub New()
    End Sub
    Private Shared Function Get2(Of T)(<System.Runtime.CompilerServices.CallerMemberName> Optional propertyName As String = "") As T
        If HttpContext.Current.Session(propertyName) Is Nothing Then
            Return Nothing
        End If
        Return DirectCast(HttpContext.Current.Session(propertyName), T)
    End Function

    Private Shared Sub Set2(Of T)(value As T, <System.Runtime.CompilerServices.CallerMemberName> Optional propertyName As String = "")
        HttpContext.Current.Session(propertyName) = value
    End Sub

    Public Shared Property MyInt() As Integer
        Get
            Return Get2(Of Integer)()
        End Get
        Set
            Set2(Of Integer)(value)
        End Set
    End Property
    Public Shared Property MyBool() As Boolean
        Get
            Return Get2(Of Boolean)()
        End Get
        Set
            Set2(Of Boolean)(value)
        End Set
    End Property
    Public Shared Property MyString() As String
        Get
            Return Get2(Of String)()
        End Get
        Set
            Set2(Of String)(value)
        End Set
    End Property
End Class

'=======================================================
'Service provided by Telerik (www.telerik.com)
'Conversion powered by NRefactory.
'Twitter: @telerik
'Facebook: facebook.com/telerik
'=======================================================
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top