每次都使用会话来获取/设置对象属性 [英] Using session to get/set object properties everytime

查看:28
本文介绍了每次都使用会话来获取/设置对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着搜索这个,但我什至不知道如何用词来搜索.

我试图做的是有一个类,每次我访问它来更改它时,我真的从会话中获取和设置值.

这是我正在尝试做的事情(到目前为止我所做的.):

公共类示例{公共 int prop1 {get;set;}公共静态示例实例{return (example)(HttpContext.Current.Session["exampleClass"] ?? new example());}}公开课主要{protected void Page_Load(object sender, EventArgs e){example.Instance.prop1 = "aaa";//将值存储到会话中txtInput.Text = example.Instance.prop1;//从会话中检索值}}

我希望这对我正在尝试做的事情有意义.

任何帮助将不胜感激,谢谢.

解决方案

看起来您已经很接近了,但实际上您没有任何东西可以在会话中存储对象.尝试这样的事情:

公共静态示例实例{得到{//如果尚未存储对象,则将其存储在会话中如果(会话[示例"] == null)会话["示例"] = 新示例();//从会话返回对象返回(示例)会话[示例"];}}

这基本上只是单例模式的网络友好实现.>

I tried searching for this but I'm not even sure how to phrase it for the search.

What I'm attempting to do is have a class that everytime I access it to change it, I'm really getting and setting the value from session.

Here's what I'm trying to do (what I have so far.):

public class example
{
   public int prop1 {get;set;}

   public static example Instance
   {
       return (example)(HttpContext.Current.Session["exampleClass"] ?? new example());
   }

}

public class main
{
   protected void Page_Load(object sender, EventArgs e)
   {
      example.Instance.prop1 = "aaa"; //stores value into session
      txtInput.Text = example.Instance.prop1; //retrieves value from session
   }
}

I hope that makes sense on what I am trying to do.

Any help would be appreciated, thank you.

解决方案

It looks like you're pretty close, but you don't have anything to actually store the object in session. Try something like this:

public static Example Instance
{
    get
    {
        //store the object in session if not already stored
        if (Session["example"] == null)
            Session["example"] = new Example();

        //return the object from session
        return (Example)Session["example"];
    }
}

This is basically just a web-friendly implementation of the Singleton Pattern.

这篇关于每次都使用会话来获取/设置对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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