试图了解?C#中的(空条件)运算符 [英] Trying to understand ?. (null-conditional) operator in C#
本文介绍了试图了解?C#中的(空条件)运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个非常简单的示例:
I have this very simple example:
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");
}
}
}
if(list?.Count> 0)
行可以完美编译,这意味着如果 list
为 null
,则表达式计数>默认情况下,0
变为 false
.
The line if (list?.Count > 0)
compiles perfectly which means that if list
is null
, the expression Count > 0
becomes false
by default.
但是,行 if(a?.B)
引发编译器错误,提示我无法将 bool?
隐式转换为 bool
However, the line if (a?.B)
throws a compiler error saying I can't implicitly convert bool?
to bool
.
为什么一个与另一个不同?
Why is one different from the other?
推荐答案
-
list?.Count>0
:在这里,您将int?
与int
进行比较,产生bool
,因为list?.Count > 0
: Here you compare anint?
to anint
, yielding abool
, since lifted comparison operators return abool
, not abool?
.a?.B
: Here, you have abool?
.if
, however, requires abool
.
这篇关于试图了解?C#中的(空条件)运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文