检查空值的正确方法是什么? [英] What is the proper way to check for null values?
问题描述
我喜欢空合并运算符,因为它可以轻松地为可空类型分配默认值.
I love the null-coalescing operator because it makes it easy to assign a default value for nullable types.
int y = x ?? -1;
那太好了,除非我需要用 x
做一些简单的事情.例如,如果我想检查 Session
,那么我通常最终不得不写一些更详细的东西.
That's great, except if I need to do something simple with x
. For instance, if I want to check Session
, then I usually end up having to write something more verbose.
我希望我能做到这一点:
I wish I could do this:
string y = Session["key"].ToString() ?? "none";
但是你不能,因为 .ToString()
在空检查之前被调用,所以如果 Session["key"]
为空,它会失败.我最终这样做了:
But you can't because the .ToString()
gets called before the null check so it fails if Session["key"]
is null. I end up doing this:
string y = Session["key"] == null ? "none" : Session["key"].ToString();
在我看来,它比三行替代方案更有效:
It works and is better, in my opinion, than the three-line alternative:
string y = "none";
if (Session["key"] != null)
y = Session["key"].ToString();
即使这样有效,我仍然很好奇是否有更好的方法.似乎不管我总是要引用 Session["key"]
两次;一次是检查,一次是分配.有什么想法吗?
Even though that works I am still curious if there is a better way. It seems no matter what I always have to reference Session["key"]
twice; once for the check, and again for the assignment. Any ideas?
推荐答案
怎么样
string y = (Session["key"] ?? "none").ToString();
这篇关于检查空值的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!