以下声明是否合法:
if(Cache[CACHE_KEY] == null)
{
//do something to form cache
}
else
{
//do something else that uses cache
}
我不确定我的程序是否真的正常运行(即使它编译)并且想知道缓存是否不存在是否设置为空?
最佳答案
是的,那是合法的(但标题中的问题不是,详见下文)。
不过,检查缓存中的类型是否符合您的预期可能是明智的做法,而不是必须进行两次检查,例如:
//in English, the following line of code might read:
// if the item known in the cache by the specified key is in
// in fact of type MyExpectedReferenceType, then give me it
// as such otherwise, give me a null reference instead...
var myCachedInstance = Cache[key] as MyExpectedReferenceType;
if (myCachedInstance == null)
{
//we retrieved a reference to an instance of an MyExpectedReferenceType
}
else
{
//oh, no - we didn't!
}
虽然重新阅读您的问题,并考虑到您的程序无法正常工作,但我很想说您有比这更大的问题; 如何您的程序无法正常工作? Cache
实例本身在可访问时永远不会是 null
- 它是 Page
的只读字段。但是,您预期的缓存值可能是 null
,如果这是问题所在,您应该会收到一个 NullReferenceException
- 是这样吗?
更新:
要处理您的评论,请查看我添加到代码中的评论。
关于c# - 缓存 == 空?是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5563598/