在此代码片段中,我只是将 null 放入 MemoryCache,然后检查此键是否存在:
var _cache = new MemoryCache(new MemoryCacheOptions());
_cache.Set<string>(cacheKey, null);
var isInCache = _cache.TryGetValue(cacheKey, out string nothing);
isInCache 在这种情况下为 false。这种行为是预期的吗?
我使用 .NET Core 2.2 控制台应用程序。
最佳答案
基于source code对于 TryGetValue()
,如果在检查类型 if (result is TItem item)
时返回 null,它将返回 false
。但是,.Count
属性将返回 1。(感谢 @jgoday 对这些细节的评论)。
另一种方法是使用一个“空值”(例如 Guid.NewGuid()
)来表示一个空值,这样就可以将某些内容输入到缓存中,以便您可以验证是否曾经添加过。
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;
}
}
关于c# - 内存缓存问题。 TryGetValue 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55221262/