如何创建C#会话对象包装器?

如何创建一个类库,我可以在其中获取和设置IIS Session对象,我使用var x = objectname("key")获取值或objectname("key") = x来设置值?

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

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

然后,当我需要获取或设置项目时,您只需执行以下操作:

 // Set MySessionHelper.CustomItem1 = "Hello"; // Get string test = MySessionHelper.CustomItem1; 

这是你在寻找什么?

编辑:根据我对您的问题的评论,您不应直接从您的应用程序中的页面访问会话。 包装器类不仅可以使访问类型安全,还可以为您提供进行所有更改的中心点。 使用包装器使用您的应用程序,您可以随时轻松地将Session替换为您选择的数据存储区,而无需对使用该会话的每个页面进行更改。

我喜欢使用包装器类的另一件事是它记录了会话中存储的所有数据。 下一个程序员可以通过查看包装器类来查看存储在会话中的所有内容,这样您就不太可能多次存储相同的数据或者重新获取已在会话中缓存的数据。

我想,您可以使用像Dictionary这样的通用字典或类似的东西来实现这种效果。 您必须编写一些包装代码,以便在访问非existend项时添加Object,例如Wrapper中的自定义默认属性。

你可以使用这样的东西

 public class Session { private static Dictionary _instance = new Dictionary(); private Session() { } public static Dictionary Instance { get { if(_instance == null) { _instance = new Dictionary(); } return _instance; } } } 

并像这样使用它

 Session.Instance["key"] = "Hello World";