首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用泛型避免缓存不同类型时的强制转换

使用泛型避免缓存不同类型时的强制转换
EN

Stack Overflow用户
提问于 2016-11-07 15:18:58
回答 1查看 939关注 0票数 2

我正在使用ASP.NET核心和Redis。我试图在缓存中存储不同类型的不同对象,并且希望避免显式转换。

这是我的红宝石缓存的包装器

代码语言:javascript
复制
public class RedisCacheStorage : Contracts.ICacheStorage
{
    private CachingFramework.Redis.Context _context = null;

    public RedisCacheStorage(string configuration)
    {
        _context = new CachingFramework.Redis.Context(configuration, new CachingFramework.Redis.Serializers.JsonSerializer());
    }
    public void SetItem<T>(string key, T value)
    {
        _context.Cache.SetObject<T>(key, value);
    }
    public T GetItem<T>(string key)
    {
        return _context.Cache.GetObject<T>(key);
    }

    public T GetItem<T>(string key, Func<T> loadCacheFunc)
    {
        return _context.Cache.FetchObject<T>(key, loadCacheFunc);
    }

然后我将ICacheStorage注入到CacheManager (实现ICacheManager)中。我试图隔离依赖项并保持CacheStorage的简单性,所以当我需要更改缓存类型时,我只需实现ICacheStorage。在CacheManager中,我们将在传递特殊密钥时注入获取某些数据的所有服务。

CacheManager

代码语言:javascript
复制
  public class CacheManager : Contracts.ICacheManager
{
    private Contracts.ICacheStorage _cacheStorage;
    private SecurityCore.ServiceContracts.IParametersService _paramService;
    public CacheManager(Contracts.ICacheStorage cacheStorage, SecurityCore.ServiceContracts.IParametersService paramService)
    {
        _cacheStorage = cacheStorage;
        _paramService = paramService;
    }
    public Object GetItem(string key)
    {
        if (key == Constants.CacheKeys.SecuritySystemParams)
            return _cacheStorage.GetItem<Dictionary<string, string>>(key, _paramService.GetSystemParameters);

        //if (key == Constants.CacheKeys.EffectivePermissions)
        //   return  List of Effective Permissions

        return _cacheStorage.GetItem<Object>(key);
    }

_cacheStorage.GetItem<Dictionary<string, string>>(key, _paramService.GetSystemParameters);

传递一个函数,该函数使用Redis的Fetch方法,如果缓存为空,则调用服务,然后将数据存储在缓存中并返回。

我的问题是我需要避免转换,因为我可能返回不同的对象,如何继续使用Generics,所以我传递返回对象的类型。

正如您在下面看到的编译错误,由于无法将类型对象转换为Dictionay,这需要显式转换才能解决。

有没有更好、更优雅的方法来实现整个想法?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-07 15:22:16

读取错误消息。

您需要显式指定类型参数。

通过使用类型安全的密钥,您可以做得更好:

代码语言:javascript
复制
class CacheKey<T> {
    public string Name { get; }
    public string ToString() => Name;
    public CacheKey(string name) { Name = name; }
}

public T GetItem<T>(CacheKey<T> key) { ... }

public CacheKey<Dictionary<string, string>> SecuritySystemParams { get; } = new CacheKey<Dictionary<string, string>>("SecuritySystemParams");

这将使GetItem()从键中推断出T,并防止您传递错误的类型。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40468614

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档