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

前端 未结 9 697
陌清茗
陌清茗 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:58

    I'm facing your question when I'm using the null check operator ?.:

    if (!RolesList?.Any()) //Not accepted: cannot convert bool? to bool
    

    So I'm using this instead

    if (RolesList?.Any() != true)
      //value is null or false
    

    In your case you should set it like so:

    obj.IsVisible = chkDisplayStuff.IsChecked ?? false;
    
    0 讨论(0)
  • 2020-12-05 07:00

    You've declared IsChecked as a bool? (Nullable<bool>). A nullable boolean can be either true, false or null. Now ask yourself: If IsChecked was null, then what value should be assigned to IsDisplay (which can only take a true or false)? The answer is that there is no correct answer. An implicit cast here could only produce hidden trouble, which is why the designers decided to only allow an explicit conversion and not an implicit one.

    0 讨论(0)
  • 2020-12-05 07:04

    You can use below code

    obj.IsDisplay = chkDisplay.IsChecked == true?true:false;
    
    0 讨论(0)
提交回复
热议问题