63

我有这个非常简单的例子:

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)编译完美,这意味着 if listis null,表达式默认Count > 0变为false

但是,该行if (a?.B)会引发编译器错误,提示我无法隐式转换bool?bool.

为什么一个与另一个不同?

4

2 回答 2

78
于 2016-06-29T15:31:01.143 回答
40

在您的第一种情况 ( list?.Count) 中,运算符返回int?一个 -a 可为空的int
>运算符是为可为空的整数定义的,因此如果int?没有值(为空),则比较将返回false

在您的第二个示例 ( a?.B)bool?中,返回 a(因为 ifa为 null,既不返回true也不返回falsebut null)。并且bool?不能在if语句中使用,因为该if语句需要 (non-nullable) bool

您可以将该语句更改为:

if (a?.B ?? false)

让它再次工作。因此,当空条件运算符 ( ??) 返回时,空合并运算符 ( ) 返回。false?.null

或者(正如 TheLethalCoder 建议的那样):

if (a?.B == true)
于 2016-06-29T15:31:41.630 回答