试图了解?C#中的(空条件)运算符 [英] Trying to understand ?. (null-conditional) operator in C#

查看:51
本文介绍了试图了解?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?

推荐答案

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆