在这个代码片段中,我只在MemoryCache中放置null,然后检查这个键是否存在:
var _cache = new MemoryCache(new MemoryCacheOptions());
_cache.Set<string>(cacheKey, null);
var isInCache = _cache.TryGetValue(cacheKey, out string nothing);在这种情况下,isInCache是错误的。这是预期的行为吗?
我使用.NET Core2.2控制台应用程序。
发布于 2019-03-18 12:42:03
根据源代码 for 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;
}
}https://stackoverflow.com/questions/55221262
复制相似问题