cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)

前端 未结 9 696
陌清茗
陌清茗 2020-12-05 06:14

Error : cannot implicitly convert type \'bool?\' to \'bool\'. An explicit conversion exists (are you missing a cast?)

Code :



        
相关标签:
9条回答
  • 2020-12-05 06:43

    Try this

    if (asset.IsUp ?? false)
    
    0 讨论(0)
  • 2020-12-05 06:44

    bool is not equal to bool?.

    bool can take two values, true and false.

    bool? can take three, true, false, and null.

    That is why they are different.

    0 讨论(0)
  • 2020-12-05 06:46

    As the others stated bool? is not equal to bool. bool? can also be null, see Nullable<t> (msdn).

    If you know what the null state wants to imply, you easily can use the ?? - null-coalescing operator (msdn) to convert your bool? to bool without any side effects (Exception).

    Example:

    //Let´s say "chkDisplay.IsChecked = null" has the same meaning as "chkDisplay.IsChecked = false" for you
    //Let "check" be the value of "chkDisplay.IsChecked", unless "chkDisplay.IsChecked" is null, in which case "check = false"
    
    bool check = chkDisplay.IsChecked ?? false;
    
    0 讨论(0)
  • 2020-12-05 06:48

    bool? is not a bool. It is in reality a Nullable<bool> http://msdn.microsoft.com/en-us/library/b3h38hb0(v=vs.110).aspx

    If you need the bool value then you should either cast like you are doing or call the .Value property on the bool?. There is also a .HasValue property you can check to make sure that it is not null.

    If IsChecked is null, this line will error.

    obj.IsDisplay = (bool) chkDisplay.IsChecked;
    
    0 讨论(0)
  • 2020-12-05 06:48

    cast your nullable value to value type

    [HttpPost]
    public ActionResult Index(bool? checkOffAge)
    {
        if (checkOffAge != null) {
           model.CheckOffAge =(bool)checkOffAge;
        }
    }
    
    0 讨论(0)
  • 2020-12-05 06:55

    chkDisplay.IsChecked is of type bool?. Which means it can hold values true, false and null. However, obj.IsDisplay is of type bool. Which means it can only hold true or false.

    Hence you have to explicitly cast it to type bool. However, this will still throw an exception if, the value you are trying to cast to bool is null.

    bool? nullableBool = null;
    bool notNullableBool = (bool)nullableBool; //This will throw InvalidOperationException
    
    0 讨论(0)
提交回复
热议问题