[英]Using the Null Conditional Operator to check values on objects which might be null
[英]Using the conditional operator ? to check for null session variable
看看这段代码:
System.Web.SessionState.HttpSessionState ss = HttpContext.Current.Session["pdfDocument"] ?? false;
if ((Boolean)ss)
{
Label1.Text = (String)Session["docName"];
}
基本上我想检查HttpContext.Current.Session [“pdfDocument”]是否为空,如果不是强制转换为布尔值,则检查其是真还是假。
我试图避免嵌套的if语句,并认为有一种更优雅的方式来做到这一点。 因此,我只对包含条件的答案感兴趣? 运营商。
有小费吗?
为什么使用ss变量?
那这个呢:
if (HttpContext.Current.Session["pdfDocument"] != null)
{
Label1.Text = (String)Session["docName"];
}
object ss = HttpContext.Current.Session["pdfDocument"] ?? false;
if ((Boolean)ss)
{
Label1.Text = (String)Session["docName"];
}
不确定你要求的是什么,怎么样:
System.Web.SessionState.HttpSessionState ss;
Label1.Text = (Boolean)((ss = HttpContext.Current.Session["pdfDocument"]) ?? false) ? (String)Session["docName"] : Label1.Text;
应该让ss具有有效会话或null,避免尝试将false存储到ss并完全跳过后续'if'的问题。 虽然有重复的Label1.Text。
注意:这已经过编辑,以考虑下面戴夫的评论。
问题是你不能这样做:
SessionState.HttpSessionState ss = false;
尝试将嵌套的ifs放入扩展方法,然后调用它。
你可以试试这个,虽然我不知道它是否适合你的美学:
bool isPdfDocumentSet =
bool.TryParse((HttpContext.Current.Session["pdfDocument"] as string,
out isPdfDocumentSet)
? isPdfDocumentSet
: false;
编辑:实际上有一种更简洁的方法:
bool isPdfDocumentSet =
bool.TryParse(HttpContext.Current.Session["pdfDocument"] as string,
out isPdfDocumentSet) && isPdfDocumentSet;
HttpContext.Current.Session
是一个System.Web.SessionState.HttpSessionState
对象,它是一个可以称之为不同对象的哈希或字典,所以除非你将HttpSessionState
对象存储为“pdfDocument”位置,否则行不正确。
如果您实际上在“pdfDocument”位置存储bool
,该位置可能已经或可能不在此插槽中,您可以将其直接转换为bool并将null合并为: var ss = (bool)(HttpContext.Current.Session["pdfDocument"] ?? false);
。
如果您可能在“pdfDocument”位置存储其他类型的对象,您可以通过检查null来查看它当前是否位于该位置: var ss = HttpContext.Current.Session["pdfDocument"] != null;
。
我认为你最接近解决方案的方法是:
System.Web.SessionState.HttpSessionState ss = HttpContext.Current.Session["pdfDocument"];
if (ss != null)
{
Label1.Text = (String)Session["docName"];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.