缓存==空?是否可以?
做出以下声明是否合法:
if(Cache[CACHE_KEY] == null)
{
//do something to form cache
}
else
{
//do something else that uses cache
}
我不确定我的程序实际上是否正常运行(即使它编译)并且想知道缓存是否不存在是否设置为空?
Is it legal to make the following statement:
if(Cache[CACHE_KEY] == null)
{
//do something to form cache
}
else
{
//do something else that uses cache
}
I'm not sure my program is actually functioning properly (even though it compiles) and am wondering if a cache doesn't exist is it set to null?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,这是合法的(但标题中的问题不合法,请参阅下文了解详细信息)。
不过,检查缓存中的类型是否是您期望的类型可能是明智的,而不是必须执行两次此检查,例如:
在重新阅读您的问题时,并考虑您的程序无法正常工作好吧,我很想说你有比这更大的问题; 如何您的程序无法正常运行?
Cache
实例本身在可访问时永远不会为null
- 它是Page
的只读字段。但是,您预期的缓存值可能为null
,如果这是问题所在,您应该收到NullReferenceException
- 是这样吗?更新:
要解决您的评论,请查看我添加到代码中的评论。
Yes, that is legal (but the question in the title is not, see below for details).
Though, it may be wise to check that the type in the cache is what you're expecting rather than having to do this check twice, such as:
On re-reading your question though, and thinking about your program not working properly, I'm tempted to say you have bigger issues than this; how is your program not working correctly? The
Cache
instance itself will never benull
while accessible - it is a read-only field ofPage
. However, your expected cached value could benull
and, if this is the problem, you should be receiving aNullReferenceException
- is that the case?UPDATE:
To address your comment, check out the comments I added to the code.
非常合法;相反,在执行操作之前最好检查值,尤其是确保密钥没有滑出或过期等。
Very much legal; rather its better to check for a value before performing action, especially to make sure that key has not slided-out, or expired, etc.
您发布的代码中存在潜在的竞争条件:
最好首先从缓存中提取对象,然后测试它是否为空,例如:
There is a potential race condition in the code you posted:
It's better to first extract the object from the cache, then test it for null, e.g.:
是的,这是可能的,缓存将始终被初始化(如会话和应用程序对象)
但你可以检查缓存中的某个键是否为空
Yes it`s possible, Cache will always be initialize (like session and application obj)
But you can check if a key in the cache is null