【问题标题】:C#: Using null conditional operator("?.") with "fucntion that returns a bool value"C#:将 null 条件运算符 (\"?.\") 与“返回布尔值的函数”结合使用
【发布时间】:2023-01-06 00:11:31
【问题描述】:
using System;

public class A{
    public bool func(){
        return true;
    }
    

    public int func2(){
        return 10;
    }
}

public class HelloWorld
{
    public static void Main(string[] args)
    {
        A a = new A();
        if(a?.func()){
            Console.WriteLine("true"); // Error
        }
        
        if(a?.func2() == 10){
            Console.WriteLine("true"); // print: True
        }
    }
}

像上面的情况一样,我想将 null 条件运算符与返回 bool 值的函数一起使用。 但是,它仅在与 bool 返回函数一起使用时抛出错误。

我能知道为什么它会这样吗?

具有讽刺意味的是,它很适合这个短语

if(a?.func() == true){
    Console.WriteLine("true"); // print: true
}

【问题讨论】:

    标签: c# null nullable null-conditional-operator


    【解决方案1】:

    请注意,即使 func 返回 bool

     a?.func()
    

    返回 bool?truefalse 和...null)。所以你可以把

     if (a?.func() == true)
    

    或使用??null映射到truefalse

     // in case of null - when `a` is null - assume true
     if (a?.func() ?? true)
    

    【讨论】:

      猜你喜欢
      • 2010-12-19
      • 2020-11-25
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      • 2013-06-18
      • 2017-01-09
      • 1970-01-01
      • 2020-07-09
      相关资源
      最近更新 更多