C#类型安全的通用缓存

C#类型安全的通用缓存,c#,generics,caching,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 ca

我正在寻找一种为任何对象提供通用本地缓存的方法。代码如下:

    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];
    }   
专用静态只读字典\u缓存
=新字典();
//泛型参数允许缓存空值
私有静态void AddToCache(字符串键,T值)
{
if(!_cache.ContainsKey(typeof(T)))
_Add(typeof(T),newdictionary());
_cache[typeof(T)][key]=值;
}
私有静态T GetFromCache(字符串键)
{
返回(T)_缓存[typeof(T)][key];
}   
1-有没有办法不强制转换getfromcache方法

2-在第二个词汇表中是否有确保类型安全的方法,比如说所有对象都具有相同的类型。(这是由addToCache方法提供的,但我更喜欢在设计中使用类型控件)。对于eg,具有以下类型的_缓存

    Dictionary<Type,Dictionary<string,typeof(type)>>
字典
Thx

试试这个:

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];
}
静态类助手
{
内部静态只读字典缓存=新建字典();
}
私有静态void AddToCache(字符串键,T值)
{
Helper.cache[key]=值;
}
私有静态T GetFromCache(字符串键)
{
返回Helper.cache[key];
}
试试这个:

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];
}
静态类助手
{
内部静态只读字典缓存=新建字典();
}
私有静态void AddToCache(字符串键,T值)
{
Helper.cache[key]=值;
}
私有静态T GetFromCache(字符串键)
{
返回Helper.cache[key];
}

为什么不将泛型参数放在类声明中:

public class Cache<T>
{
    private Dictionary<string, T> _cache = new Dictionary<string, T>();
    ...

}
公共类缓存
{
私有字典_cache=新字典();
...
}

它可以是静态的,如果您喜欢

为什么不将泛型参数放在类声明中:

public class Cache<T>
{
    private Dictionary<string, T> _cache = new Dictionary<string, T>();
    ...

}
公共类缓存
{
私有字典_cache=新字典();
...
}

如果您喜欢,它可以是静态的。如果您在编译时不知道所需的类型,则无法创建强类型的缓存。如果您在运行时之前不知道所需的类型,那么您的问题的答案恐怕是否定的。

如果您在编译时不知道所需的类型,您将无法创建强类型的缓存。如果您在运行时之前不知道所需的类型,那么您的问题的答案恐怕是否定的。

除非原语类型没有装箱,否则您不会从中获得太多好处

private static readonly Dictionary<Type,Dictionary<string,object>> _cache 
    = new Dictionary<Type, IDictionary>();

//The generic parameter allow null values to be cached
private static void AddToCache<T>(string key, T value)
{
    // create a dictionary of the correct type
    if(!_cache.ContainsKey(typeof(T)))
        _cache.Add(typeof(T),new Dictionary<string, T>());

    _cache[typeof (T)][key] = value;
}

private static T GetFromCache<T>(string key)
{
    // casting the dictionary instead of the value
    Dictionary<string, T> typedDictionary = (Dictionary<string, T>)_cache[typeof (T)];
    return typedDictionary[key];
}
专用静态只读字典\u缓存
=新字典();
//泛型参数允许缓存空值
私有静态void AddToCache(字符串键,T值)
{
//创建正确类型的词典
if(!_cache.ContainsKey(typeof(T)))
_Add(typeof(T),newdictionary());
_cache[typeof(T)][key]=值;
}
私有静态T GetFromCache(字符串键)
{
//强制转换字典而不是值
字典类型字典=(字典)u缓存[typeof(T)];
返回类型字典[键];
}

当然,它需要更多的未找到处理。

除非原语类型没有装箱,否则您不会从中获得太多好处

private static readonly Dictionary<Type,Dictionary<string,object>> _cache 
    = new Dictionary<Type, IDictionary>();

//The generic parameter allow null values to be cached
private static void AddToCache<T>(string key, T value)
{
    // create a dictionary of the correct type
    if(!_cache.ContainsKey(typeof(T)))
        _cache.Add(typeof(T),new Dictionary<string, T>());

    _cache[typeof (T)][key] = value;
}

private static T GetFromCache<T>(string key)
{
    // casting the dictionary instead of the value
    Dictionary<string, T> typedDictionary = (Dictionary<string, T>)_cache[typeof (T)];
    return typedDictionary[key];
}
专用静态只读字典\u缓存
=新字典();
//泛型参数允许缓存空值
私有静态void AddToCache(字符串键,T值)
{
//创建正确类型的词典
if(!_cache.ContainsKey(typeof(T)))
_Add(typeof(T),newdictionary());
_cache[typeof(T)][key]=值;
}
私有静态T GetFromCache(字符串键)
{
//强制转换字典而不是值
字典类型字典=(字典)u缓存[typeof(T)];
返回类型字典[键];
}

当然,它需要更多的未发现处理。

可能需要添加一些锁和一些克隆。。。但这应该可以

class Program
{
    static void Main(string[] args)
    {
        CacheObject<int>.Instance["hello"] = 5;
        CacheObject<int>.Instance["hello2"] = 6;
        CacheObject<string>.Instance["hello2"] = "hi";
        Console.WriteLine(CacheObject<string>.Instance["hello2"]); //returns hi
    }
}

public class CacheObject<V> : CacheObject<string, V> { }
public class CacheObject<K,V>
{
    private static CacheObject<K, V> _instance = new CacheObject<K, V>();
    public static CacheObject<K, V> Instance { get { return _instance; } }

    private Dictionary<K, V> _store = new Dictionary<K, V>();
    public T this[K index]
    {
        get { return _store.ContainsKey(index) ? _store[index] : default(V); }
        set
        {
            if (_store.ContainsKey(index)) _store.Remove(index);
            if (value != null) _store.Add(index, value);
        }
    }
}
类程序
{
静态void Main(字符串[]参数)
{
CacheObject.Instance[“hello”]=5;
CacheObject.Instance[“hello2”]=6;
CacheObject.Instance[“hello2”]=“hi”;
Console.WriteLine(CacheObject.Instance[“hello2”]);//返回hi
}
}
公共类CacheObject:CacheObject{}
公共类缓存对象
{
私有静态CacheObject_实例=新CacheObject();
公共静态CacheObject实例{get{return}
私有字典_store=新字典();
公共T此[K索引]
{
获取{return _store.ContainsKey(索引)?_store[index]:默认值(V);}
设置
{
如果(_store.ContainsKey(index))_store.Remove(index);
if(value!=null)\ u store.Add(索引,值);
}
}
}

可能需要添加一些锁和一些克隆。。。但这应该可以

class Program
{
    static void Main(string[] args)
    {
        CacheObject<int>.Instance["hello"] = 5;
        CacheObject<int>.Instance["hello2"] = 6;
        CacheObject<string>.Instance["hello2"] = "hi";
        Console.WriteLine(CacheObject<string>.Instance["hello2"]); //returns hi
    }
}

public class CacheObject<V> : CacheObject<string, V> { }
public class CacheObject<K,V>
{
    private static CacheObject<K, V> _instance = new CacheObject<K, V>();
    public static CacheObject<K, V> Instance { get { return _instance; } }

    private Dictionary<K, V> _store = new Dictionary<K, V>();
    public T this[K index]
    {
        get { return _store.ContainsKey(index) ? _store[index] : default(V); }
        set
        {
            if (_store.ContainsKey(index)) _store.Remove(index);
            if (value != null) _store.Add(index, value);
        }
    }
}
类程序
{
静态void Main(字符串[]参数)
{
CacheObject.Instance[“hello”]=5;
CacheObject.Instance[“hello2”]=6;
CacheObject.Instance[“hello2”]=“hi”;
Console.WriteLine(CacheObject.Instance[“hello2”]);//返回hi
}
}
公共类CacheObject:CacheObject{}
公共类缓存对象
{
私有静态CacheObject_实例=新CacheObject();
公共静态CacheObject实例{get{return}
私有字典_store=新字典();
公共T此[K索引]
{
获取{return _store.ContainsKey(索引)?_store[index]:默认值(V);}
设置
{
如果(_store.ContainsKey(index))_store.Remove(index);
if(value!=null)\ u store.Add(索引,值);
}
}
}
自举:

services.AddMemoryCache();
用法:

public class HomeController : Controller
{
    private IMemoryCache _cache;

    public HomeController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;

        var onlineAt = _cache.Get<DateTime?>("self:startup");
    }
公共类HomeController:控制器
{
私有IMemoryCache\u缓存;
公共家庭控制器(IMemoryCache memoryCache)
{
_cache=memoryCache;
var onlineAt=_cache.Get(“self:startup”);
}
有关写入和引导的详细信息,请查看上面的链接。它结合了我的答案中的大部分内容。您还可以使用
Microsoft.Extensions.Caching.Redis
或ot