Tot*_*oto 1 c# generics caching
我正在寻找一种方法来为任何对象提供通用的本地缓存.这是代码:
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];
}
Run Code Online (Sandbox Code Playgroud)
1-有没有办法不使用getfromcache方法?
2-有没有办法确保第二个字典中的类型安全,说所有对象都具有相同的类型.(这是由addToCache方法提供的,但我更喜欢设计中的类型控件).例如,要具有以下类型的_cache
Dictionary<Type,Dictionary<string,typeof(type)>>
Run Code Online (Sandbox Code Playgroud)
谢谢
Dan*_*iel 12
试试这个:
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];
}
Run Code Online (Sandbox Code Playgroud)