3

看看这段代码:

System.Web.SessionState.HttpSessionState ss = HttpContext.Current.Session["pdfDocument"] ?? false;

        if ((Boolean)ss)
        {
            Label1.Text = (String)Session["docName"];
        }

基本上我想检查 HttpContext.Current.Session["pdfDocument"] 是否不为空,如果它不转换为布尔值,那么检查它的真假。

我试图避免嵌套 if 语句,并认为会有一种更优雅的方式来做到这一点。因此,我只对包含条件的答案感兴趣?操作员。

有小费吗?

4

7 回答 7

4

Why do you use ss variable?

What about this:

if (HttpContext.Current.Session["pdfDocument"] != null)
{
    Label1.Text = (String)Session["docName"];
}
于 2010-10-13T12:10:24.620 回答
2
    object ss = HttpContext.Current.Session["pdfDocument"] ?? false; 
    if ((Boolean)ss) 
    { 
        Label1.Text = (String)Session["docName"]; 
    } 
于 2010-10-13T12:08:49.017 回答
1

Not sure exactly what you're asking for, how about:

System.Web.SessionState.HttpSessionState ss;

Label1.Text = (Boolean)((ss = HttpContext.Current.Session["pdfDocument"]) ?? false) ? (String)Session["docName"] : Label1.Text;

Should leave ss with either a valid session or null, avoids the problem of trying to store false to ss and completely skips the subsequent 'if'. Though there's a repetition of Label1.Text.

Note: this has been edited to take account of the comment by Dave below.

于 2010-10-13T12:11:31.933 回答
0

你可以试试这个,虽然我不知道它是否符合你的审美:

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;
于 2010-10-13T12:19:46.367 回答
0

HttpContext.Current.Session是一个System.Web.SessionState.HttpSessionState对象,它是不同对象的散列或字典,有些人可能称之为字典,因此除非您将HttpSessionState对象存储为“pdfDocument”位置,否则第一行是不正确的。

如果您实际上将 a 存储bool在“pdfDocument”位置中,该位置可能已经或可能不在此插槽中,您可以将其直接转换为 bool 并 null 合并它:var ss = (bool)(HttpContext.Current.Session["pdfDocument"] ?? false);.

如果您可能在“pdfDocument”位置存储某种其他类型的对象,您可以通过检查 null: 来查看它当前是否在该位置var ss = HttpContext.Current.Session["pdfDocument"] != null;

于 2010-10-13T12:22:57.703 回答
0

问题是你不能这样做:

SessionState.HttpSessionState ss = false;

尝试将嵌套的 ifs 放入扩展方法中,然后改为调用它。

于 2010-10-13T12:06:13.483 回答
-1

我认为您最接近采用该路径的解决方案如下:

System.Web.SessionState.HttpSessionState ss = HttpContext.Current.Session["pdfDocument"];
if (ss != null)
{
    Label1.Text = (String)Session["docName"];
}
于 2010-10-13T12:08:10.950 回答