Dee*_*ena 62 c# nullable roslyn c#-6.0 null-conditional-operator
我有一个非常简单的例子:
class Program
{
class A
{
public bool B;
}
static void Main()
{
System.Collections.ArrayList list = null;
if (list?.Count > 0)
{
System.Console.WriteLine("Contains elements");
}
A a = null;
if (a?.B)
{
System.Console.WriteLine("Is initialized");
}
}
}
Run Code Online (Sandbox Code Playgroud)
行if (list?.Count > 0)编译完美,这意味着如果list是null,表达式Count > 0变为false默认.
但是,该行if (a?.B)抛出编译器错误,表示我无法隐式转换bool?为bool.
为什么一个人与另一个人不同?
Hei*_*nzi 75
list?.Count > 0:在这里你比较a int?和a int,产生a bool,因为提升的比较运算符返回a bool,而不是abool?.a?.B:在这里,你有一个bool?.if但是,需要一个bool.Ren*_*ogt 38
在你的第一个case(list?.Count)中,运算符返回int?一个可空的int.
该>经营者可为空整数定义,因此,如果int?没有值(为空),比较会返回false.
在你的第二个例子中,(a?.B)bool?返回一个(因为如果a为null,既不是true也不是,false而是null返回).并且bool?不能在if语句中使用,因为if语句需要(不可为空)bool.
您可以将该语句更改为:
if (a?.B ?? false)
Run Code Online (Sandbox Code Playgroud)
让它再次运作.因此,当??返回falsenull条件operator(?.)时,null-coalescing operator()返回null.
或者(正如TheLethalCoder建议的那样):
if (a?.B == true)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5760 次 |
| 最近记录: |