首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >内存缓存问题。TryGetValue返回false

内存缓存问题。TryGetValue返回false
EN

Stack Overflow用户
提问于 2019-03-18 12:19:28
回答 1查看 5.9K关注 0票数 9

在这个代码片段中,我只在MemoryCache中放置null,然后检查这个键是否存在:

代码语言:javascript
复制
        var _cache = new MemoryCache(new MemoryCacheOptions());
        _cache.Set<string>(cacheKey, null);
        var isInCache = _cache.TryGetValue(cacheKey, out string nothing);

在这种情况下,isInCache是错误的。这是预期的行为吗?

我使用.NET Core2.2控制台应用程序。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-18 12:42:03

根据源代码 for TryGetValue(),如果在检查if (result is TItem item)类型时返回null,它将返回false。但是,.Count属性将返回1 (这些细节要感谢@jgoday注释)。

另一种方法是有一个‘空值’(例如Guid.NewGuid()),您可以使用它来表示空值,这样就可以将一些东西输入缓存中,从而验证它是否被添加过。

代码语言:javascript
复制
public class MyCache
{
  private MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
  private string nullValue = Guid.NewGuid().ToString();

  public void Set(string cacheKey, string toSet)
    => _cache.Set<string>(cacheKey, toSet == null ? nullValue : toSet);

  public string Get(string cacheKey)
  {
    var isInCache = _cache.TryGetValue(cacheKey, out string cachedVal);
    if (!isInCache) return null;

    return cachedVal == nullValue ? null : cachedVal;
  }
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55221262

复制
相关文章

相似问题

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