C#泛型缓存,类型安全

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)

  • +1,更好,因为每种类型现在都有自己的“命名空间”。不利的一面是,最好不要从多个线程中使用它。 (2认同)
  • 有点hacky,但好主意。如果与 ConcurrentDictionary 结合使用,这可能会很好地工作 (2认同)