在此代码片段中,我只是在 MemoryCache 中放置了 null,然后检查此键是否存在:
var _cache = new MemoryCache(new MemoryCacheOptions());
_cache.Set<string>(cacheKey, null);
var isInCache = _cache.TryGetValue(cacheKey, out string nothing);
Run Code Online (Sandbox Code Playgroud)
在这种情况下 isInCache 为假。这种行为是预期的吗?
我使用 .NET Core 2.2 控制台应用程序。
Based on the source code for TryGetValue() it will return false if null is returned when it checks type if (result is TItem item). However, the .Count property would return 1. (thanks to @jgoday comment for these details).
An alternative is to have a 'null value' (e.g. Guid.NewGuid()) that you can use to represent a null value, this way something is entered into the cache so you can verify whether it has ever been added.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3300 次 |
| 最近记录: |