Ho scritto i seguenti metodi di estensione per Session in modo che possa persistere e recuperare gli oggetti in base al loro tipo. Funziona bene per la mia soluzione, ma alla fine ho dovuto duplicare i miei metodi di estensione per coprire il vecchio HttpSessionState e il nuovo HttpSessionStateBase. Mi piacerebbe trovare un modo per ridurli a un set che copre entrambi i tipi. qualche idea?Come posso scrivere estensioni per Session senza dover scrivere metodi separati per HttpSessionState e 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
}