我爲會話編寫了以下擴展方法,以便可以通過其類型持久保存和檢索對象。這適用於我的解決方案,但最終我不得不復制我的擴展方法來覆蓋舊的HttpSessionState和新的HttpSessionStateBase。我想找到一種方法讓這些回到兩套類型。有什麼想法嗎?如何爲Session創建擴展而無需爲HttpSessionState和HttpSessionStateBase編寫單獨的方法?
public static class SessionExtensions
{
#region HttpSessionStateBase
public static T Get<T>(this HttpSessionStateBase session)
{
return session.Get<T>(typeof(T).Name);
}
public static T Get<T>(this HttpSessionStateBase session, string key)
{
var obj = session[key];
if(obj == null || typeof(T).IsAssignableFrom(obj.GetType()))
return (T) obj;
throw new Exception("Type '" + typeof(T).Name + "' doesn't match the type of the object retreived ('" + obj.GetType().Name + "').");
}
public static void Put<T>(this HttpSessionStateBase session, T obj, string key)
{
session[key] = obj;
}
public static void Put<T>(this HttpSessionStateBase session, T obj)
{
session.Put(obj, typeof(T).Name);
}
#endregion
#region HttpSessionState
public static T Get<T>(this HttpSessionState session)
{
return session.Get<T>(typeof(T).Name);
}
public static T Get<T>(this HttpSessionState session, string key)
{
var obj = session[ key ];
if(obj == null || typeof(T).IsAssignableFrom(obj.GetType()))
return (T) obj;
throw new Exception("Type '" + typeof(T).Name + "' doesn't match the type of the object retreived ('" + obj.GetType().Name + "').");
}
public static void Put<T>(this HttpSessionState session, T obj)
{
session.Put(obj, typeof(T).Name);
}
public static void Put<T>(this HttpSessionState session, T obj, string key)
{
session[ key ] = obj;
}
#endregion
}