简体   繁体   English

对 ? 的行为感到困惑。 操作员

[英]Confused about behavior of ?. operator

Here is my code这是我的代码

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");
        }
    }
}

The output of this program这个程序的输出

Its an apartment它的公寓

According to the definition of ?.根据?的定义 operator操作员

if one operation in a chain of conditional member or element access operations returns null, the rest of the chain doesn't execute.如果条件成员或元素访问操作链中的一个操作返回 null,则链的其余部分不会执行。

In this case, Address object is null, I don't understand why it's not going in the else branch of the code here?在这种情况下,Address 对象为空,我不明白为什么它不在代码的 else 分支中?

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");
}

This is correct, the rest of the chain doesn't execute, null-coalescing operator ??这是正确的,链的其余部分不执行,空合并运算符?? returns true .返回true According to MSDN根据MSDN

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.否则,它评估右侧操作数并返回其结果。

If you want to compare the result with either true or false (per your update) you can use如果您想将结果与truefalse (根据您的更新)进行比较,您可以使用

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

The left-hand operand returns Nullable<bool> , you can also read about it in MSDN左边的操作数返回Nullable<bool> ,你也可以在MSDN 中阅读它

更新使用快捷操作符进行以下操作的等效代码是什么?
if (employee.Address != null && ? employee.Address.IsAppartment == true)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM