C# 每次都使用会话来获取/设置对象属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10437741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using session to get/set object properties everytime
提问by JMD
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.
任何帮助将不胜感激,谢谢。
采纳答案by James Johnson
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.
这基本上只是Singleton Pattern的 Web 友好实现。
回答by Chuck Conway
This would be easy to do with generics.
使用泛型很容易做到这一点。
Give this a try.
试试这个。
public class Session
{
public User User
{
get { return Get<User>("User"); }
set {Set<User>("User", value);}
}
/// <summary> Gets. </summary>
/// <typeparam name="T"> Generic type parameter. </typeparam>
/// <param name="key"> The key. </param>
/// <returns> . </returns>
private T Get<T>(string key)
{
object o = HttpContext.Current.Session[key];
if(o is T)
{
return (T) o;
}
return default(T);
}
/// <summary> Sets. </summary>
/// <typeparam name="T"> Generic type parameter. </typeparam>
/// <param name="key"> The key. </param>
/// <param name="item"> The item. </param>
private void Set<T>(string key, T item)
{
HttpContext.Current.Session[key] = item;
}
}
回答by Kris Ivanov
public class example {
public int prop1 { get; set; }
public static example Instance {
var exampleObject = (example)(HttpContext.Current.Session["exampleClass"]
?? new example());
HttpContext.Current.Session["exampleClass"] = exampleObject;
return exampleObject;
}
}
you can optimize it further if needed
如果需要,您可以进一步优化它
回答by Adauto
using System.Web;
using System.Web.SessionState;
using System.Collections.Generic;
public static class ExampleSession
{
private static HttpSessionState session { get { return HttpContext.Current.Session; } }
public static string UserName
{
get { return session["username"] as string; }
set { session["username"] = value; }
}
public static List<string> ProductsSelected
{
get
{
if (session["products_selected"] == null)
session["products_selected"] = new List<string>();
return (List<string>)session["products_selected"];
}
}
}
and you can use it like so:
你可以像这样使用它:
public class main
{
protected void Page_Load(object sender, EventArgs e)
{
//stores value into session
ExampleSession.UserName = "foo";
ExampleSession.ProductsSelected.Add("bar");
txtInput.Text = ExampleSession.UserName; //retrieves value from session
}
}
回答by David East
If you're looking for a more object oriented way of doing session here is a good way of doing it below.
如果您正在寻找一种更面向对象的会话方式,那么下面是一个很好的方式。
UserSession Class
用户会话类
[Serializable()]
public class UserSession
{
private CurrentRecord _CurrentRecord;
public CurrentRecord CurrentRecord
{
get
{
if ((_CurrentRecord == null))
{
_CurrentRecord = new CurrentRecord();
}
return _CurrentRecord;
}
set
{
if ((_CurrentRecord == null))
{
_CurrentRecord = new CurrentRecord();
}
_CurrentRecord = value;
}
}
}
Globals Class
全局类
public static class Globals
{
public static UserSession TheUserSession
{
get
{
if ((HttpContext.Current.Session["UserSession"] == null))
{
HttpContext.Current.Session.Add("UserSession", new CurrentUserSession());
return (CurrentUserSession)HttpContext.Current.Session["UserSession"];
}
else
{
return (CurrentUserSession)HttpContext.Current.Session["UserSession"];
}
}
set { HttpContext.Current.Session["UserSession"] = value; }
}
}
CurrentRecord class
CurrentRecord 类
[Serializable()]
public class CurrentRecord
{
public int id { get; set; }
public string name { get; set; }
}
Usage in code behind
在后面的代码中的使用
public void SetRecordId(int newId)
{
Globals.TheUserSession.CurrentRecord.id = newId;
}

![C# 如何通过 [WebMethod] 返回数据表](/res/img/loading.gif)