Byr*_*ahl 6 asp.net-mvc extension-methods httpsession
我为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
}
Run Code Online (Sandbox Code Playgroud)
我找到了一个有效的答案,但有一些缺点。我希望有人能够改进它。
@Andrew Hare 说两者都没有实现公共基础或接口。嗯,事实上,他们确实这么做了。它们都实现了 IEnumerable 和 ICollection。问题是,有了这些信息,您是否想要创建扩展 IEnumerable 或 ICollection 的扩展方法,而这些方法实际上只适用于 Session?也许,也许不是。无论如何,这是一种使用同时扩展 HttpSessionState 和 HttpSessionStateBase 的扩展方法来消除重复的方法:
public static class SessionExtensions
{
public static T Get<T>( this ICollection collection )
{
return collection.Get<T>( typeof( T ).Name );
}
public static T Get<T>( this ICollection collection, string key )
{
object obj = null;
dynamic session = collection as HttpSessionState ?? ( dynamic ) ( collection as HttpSessionStateBase );
if( session != null )
{
obj = session[key];
if (obj != null && !typeof (T).IsAssignableFrom(obj.GetType()))
throw new Exception("Type '" + typeof (T).Name + "' doesn't match the type of the object retreived ('" + obj.GetType().Name + "').");
}
return (T)obj;
}
public static void Put<T>( this ICollection collection, T obj )
{
collection.Put( obj, typeof( T ).Name );
}
public static void Put<T>( this ICollection collection, T obj, string key )
{
dynamic session = collection as HttpSessionState ?? ( dynamic ) ( collection as HttpSessionStateBase );
if(session!=null)
session[ key ] = obj;
}
}
Run Code Online (Sandbox Code Playgroud)
我并不热衷于这个解决方案,但至少感觉这是朝着一个有趣的方向迈出的一步。
| 归档时间: |
|
| 查看次数: |
2172 次 |
| 最近记录: |