You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#出现Operator ||不能应用于bool和bool?类型报错如何处理

问题原因

C#中bool?(可空布尔类型)存在true/false/null三种取值,逻辑或运算符||不支持直接对bool和bool?类型的操作数执行运算,因此需要先将bool?类型的isWithinGraphQlType转换为确定的bool类型。

解决方案

以下三种写法都可以解决问题,可根据业务逻辑选择:

  • 方案1:使用??空合并运算符指定null时的默认值
    你的场景中如果isWithinGraphQlType为null(即类型FullName为空,不属于GraphQL内置类型)时,希望判定为不满足条件,可默认赋值false,修改if判断为:
    if (isMetaField || isIntrospectionSchema || isWithinGraphQlType ?? false || fieldDefinition.HasMetadata("AllowUnauthenticatedAccess"))
        return;
    
    如果业务需要null时判定为满足条件,将??后的值改为true即可。
  • 方案2:使用GetValueOrDefault()方法
    可空布尔的GetValueOrDefault()方法默认在值为null时返回false,也可显式传入默认值:
    // 空值默认返回false
    if (isMetaField || isIntrospectionSchema || isWithinGraphQlType.GetValueOrDefault() || fieldDefinition.HasMetadata("AllowUnauthenticatedAccess"))
        return;
    
    // 也可显式指定空值返回的默认值,比如true
    // isWithinGraphQlType.GetValueOrDefault(true)
    
  • 方案3:显式和true比较
    当isWithinGraphQlType为null或false时,isWithinGraphQlType == true的结果都为false,只有值为true时结果为true,效果等价于默认空值为false:
    if (isMetaField || isIntrospectionSchema || isWithinGraphQlType == true || fieldDefinition.HasMetadata("AllowUnauthenticatedAccess"))
        return;
    
    如果希望空值判定为满足条件,可改为isWithinGraphQlType != false。

内容的提问来源于stack exchange,提问作者jjnrmason

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:06:03