【问题标题】:Simple way to parse bool? in a single line解析布尔的简单方法?在一行中
【发布时间】:2016-05-12 08:56:33
【问题描述】:

我正在尝试做类似的事情:

        bool? Verified;
        Verified = Request.QueryString["verifed"]==null
? null :bool.Parse(Request.QueryString["verifed"]);

但我得到了错误:

无法确定条件表达式的类型,因为<null> 和bool 之间没有隐式转换

有没有一种简单的单行方式来做到这一点,而不是像这样:

if (Request.QueryString["confirmed"] == null)
    Confirmed = null;
else
    Confirmed = bool.Parse(Request.QueryString["confirmed"]);

【问题讨论】:

  • 我会使用bool.TryParse

标签: c# types casting type-conversion


【解决方案1】:

改变这个:

Verified = Request.QueryString["verifed"]==null? null :bool.Parse(Request.QueryString["verifed"]);

到这里:

Verified = Request.QueryString["verifed"]==null? (bool?)null :bool.Parse(Request.QueryString["verifed"]);

简单的例子是:

        bool test = true;

        var test = 1 == 1 ? true : false; // Good

        bool? test2 = true;

        var test2 = 1 == 1 ? (bool?)null : false; // Good

       var test2 = 1 == 1 ? null : false; // Error: Type of conditional expression cannot be determined because there is no implicit conversion between <null> and bool

更多信息:

C# : Implicit conversion between '<null>' and 'bool'

In C# why can't a conditional operator implicitly cast to a nullable type

【讨论】:

    【解决方案2】:

    使用default关键字;

    bool? Verified;
    Verified = Request.QueryString["verifed"] == null ? default(bool?) : bool.Parse(Request.QueryString["verifed"]);
    

    如果有人不确定,default(bool?) 的结果是 null。

    需要更多信息。阅读。

    What is the use of `default` keyword in C#?
    What does default(object); do in C#?

    【讨论】:

      【解决方案3】:

      我认为您的查询参数是空字符串,因此您在转换时收到此错误。还有为什么要使用可空bool,当值为null或“”时才放假。

      bool initialValue = false;
      bool verified = Request.QueryString["verifed"]==null || Request.QueryString["verifed"] == "" ? false:bool.TryParse(Request.QueryString["verifed"], out initialValue);
      

      【讨论】:

      • 我声明bool的原因是什么?是否 null 也是一个可接受的选项,您的解决方案会忽略 null 值,将其转换为 false
      • 看你收到null的时候想做什么,如果你想说它没有被验证,那么就用false吧。为什么要让你的逻辑复杂?
      • 在这样的查询中使用它:User.Where(u=&gt; Verified==null || Verified == u.Verified); 所以我可以搜索所有用户,只搜索那些经过验证的用户或者只搜索那些没有验证的用户
      【解决方案4】:

      您会收到错误,因为编译器尝试对 ?: 运算符(即 bool)使用相同的返回类型。

      因为您无法将null 转换为bool,您可以将bool 转换为bool?:

      Verified = Request.QueryString["verifed"] == null ? null :
         (bool?)bool.Parse(Request.QueryString["verifed"]);
      

      【讨论】:

        猜你喜欢
        • 2011-10-25
        • 1970-01-01
        • 2012-05-23
        • 1970-01-01
        • 2010-10-06
        • 2010-10-11
        • 2021-12-21
        • 2023-03-17
        • 2013-01-29
        相关资源
        最近更新 更多