【发布时间】: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