如何创建一个C#会话对象的包装? [英] How to create a C# session object wrapper?

查看:84
本文介绍了如何创建一个C#会话对象的包装?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个类库,我可以获取和设置,如IIS 会话对象,其中我用 VAR X =对象名(键)来获得的价值或对象名(键)= X 设定值?

How do I create a class library where I can get and set like the IIS Session object where I use var x = objectname("key") to get the value or objectname("key") = x to set the value?

推荐答案

通常我只是有一个封装我的会话数据,并使其类型安全的一个静态类,如:

Normally I just have a static class that wraps my session data and makes it type safe like:

public static class MySessionHelper
{
    public static string CustomItem1
    {
        get { return HttpContext.Current.Session["CustomItem1"] as string; }
        set { HttpContext.Current.Session["CustomItem1"] = value; }
    }

    public static int CustomItem2
    {
        get { return (int)(HttpContext.Current.Session["CustomItem2"]); }
        set { HttpContext.Current.Session["CustomItem2"] = value; }
    }

    // etc...
}

然后,当我需要获取或设置你只需做以下项目:

Then when I need to get or set an item you would just do the following:

// Set
MySessionHelper.CustomItem1 = "Hello";

// Get
string test = MySessionHelper.CustomItem1;

这是你要找的是什么?

Is this what you were looking for?

编辑:按我对你的问题的评论,你不应该直接从您的应用程序的网页访问会话。包装类将不仅使接入类型安全的,但也会给你一个中心点,使所有的变化。使用包装你的应用程序,你可以很容易地在任何时候换出会话供你选择的数据存储不需要更改为使用会话每一个网页。

As per my comment on your question, you shouldn't access the session directly from pages within your application. A wrapper class will make not only make the access type safe but will also give you a central point to make all changes. With your application using the wrapper, you can easily swap out Session for a datastore of your choice at any point without making changes to every single page that uses the session.

我喜欢使用一个包装类的另一件事情是,它记录所有存储在会话中的数据。下一个程序员的到来可以看出,仅仅是通过在包装类看,所以你有较少的存储相同的数据多次或重复获取是在会话已经缓存数据的机会,存储在会话中的一切。

Another thing I like about using a wrapper class is that it documents all the data that is stored in the session. The next programmer that comes along can see everything that is stored in the session just by looking at the wrapper class so you have less chance of storing the same data multiple times or refetching data that is already cached in the session.

这篇关于如何创建一个C#会话对象的包装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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