I'm looking for a way to have a generic local cache for any object. Here is the code :
private static readonly Dictionary<Type,Dictionary<string,object>> _cache
= new Dictionary<Type, Dictionary<string, object>>();
//The generic parameter allow null values to be cached
private static void AddToCache<T>(string key, T value)
{
if(!_cache.ContainsKey(typeof(T)))
_cache.Add(typeof(T),new Dictionary<string, object>());
_cache[typeof (T)][key] = value;
}
private static T GetFromCache<T>(string key)
{
return (T)_cache[typeof (T)][key];
}
1- Is there a way not to cast on the getfromcache method ?
2- Is there a way to ensure type safe in the second dictionnary, say all the object would have the same type. (This is provided by the addToCache method but I would prefer a type control in the design himself). For eg to have _cache of the following type
Dictionary<Type,Dictionary<string,typeof(type)>>
Thx
Try this:
static class Helper<T>
{
internal static readonly Dictionary<string, T> cache = new Dictionary<string, T>();
}
private static void AddToCache<T>(string key, T value)
{
Helper<T>.cache[key] = value;
}
private static T GetFromCache<T>(string key)
{
return Helper<T>.cache[key];
}
Why not just put generic parameter to class declaration:
public class Cache<T>
{
private Dictionary<string, T> _cache = new Dictionary<string, T>();
...
}
it can be static if you prefer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With