我为 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
}