我不喜欢每周类型化会话,因为每次使用都需要类型转换,所以我将所有类型/对象包装在强类型化会话包装器中。
包装基地:
public abstract class SessionBase<T> : SessionBase where T : new()
{
private static readonly Object _padlock = new Object();
private static string Key
{
get { return typeof(SessionBase<T>).FullName; }
}
public static T Current
{
get
{
var instance = HttpContext.Current.Session[Key] as T;
if (instance == null)
{
lock (SessionBase<T>._padlock)
{
if (instance == null)
{
HttpContext.Current.Session[Key] = instance = new T();
}
}
}
return instance;
}
}
public static void Clear()
{
var instance = HttpContext.Current.Session[Key] as T;
if (instance != null)
{
lock (SessionBase<T>._padlock)
{
HttpContext.Current.Session[Key] = null;
}
}
}
}
现在创建一个对象(将其标记为可序列化的帮助)
[Serializable]
public QuestionCollection
{
public QuestionCollection()
{
this.Questions = new List<Question>();
}
public List<Question> Questions { get; set; }
}
现在将 QuestionCollection 设为强类型 QuestionCollectionSession
public QuestionCollectionSession : SessionBase<QuestionCollection>
{
}
现在你可以像这样使用它:
QuestionCollectionSession.Current.Questions.Add("Are you there?");
当您想从会话中清除/删除它时:
QuestionCollectionSession.Clear();