对?的行为感到困惑。算子 [英] Confused about behavior of ?. operator

查看:90
本文介绍了对?的行为感到困惑。算子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

class Address
{
    public bool IsAppartment { get; set; }
}

class Employee
{
    public string Name { get; set; }
    public Address Address { get; set; }
}    
class Program
{
    static void Main(string[] args)
    {
        Employee employee = new Employee()
        {
            Name = "Charlie"
        };
        if (employee.Address?.IsAppartment ?? true)
        {
            Console.WriteLine("Its an apartment");
        }
        else
        {
            Console.WriteLine("No employee address or not an apartment");
        }
    }
}

该程序的输出


它的公寓

Its an apartment

?。 运算符


如果条件成员或元素链中的一个操作访问
操作返回null,则链的其余部分不执行。

if one operation in a chain of conditional member or element access operations returns null, the rest of the chain doesn't execute.

在这种情况下,Address对象为null,我不明白为什么它不在代码的else分支中?

In this case, Address object is null, I don't understand why it's not going in the else branch of the code here?

更新

下面的等效代码是什么

UPDATE
What will be equivalent code for following using short cut operators?

if (employee.Address != null && employee.Address.IsAppartment == true)
{
    Console.WriteLine("Its an apartment");
}
else
{
    Console.WriteLine("No employee address or not an apartment");
}


推荐答案

这是正确的,其余的链中的不执行,空伙伴运算符 ?? 返回 true 。根据 MSDN

This is correct, the rest of the chain doesn't execute, null-coalescing operator ?? returns true. According to MSDN


null-coalescing运算符??如果不为null,则返回其左侧
操作数的值;否则,它将评估右侧的
操作数并返回其结果。

The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result.

如果要将结果与任何一个进行比较 true false (根据您的更新),您可以使用

If you want to compare the result with either true or false (per your update) you can use

if (employee?.Address?.IsAppartment == true)
{
}

左侧操作数返回 Nullable< bool> ,您也可以在 MSDN

The left-hand operand returns Nullable<bool>, you can also read about it in MSDN

这篇关于对?的行为感到困惑。算子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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