空合并运算符是右结合的,这意味着以下形式的表达式
第一的 ??第二??第三
被评估为
第一的 ?? (第二个?第三个)
根据上述规则,我认为以下翻译是不正确的。
From:
Address contact = user.ContactAddress;
if (contact == null)
{
contact = order.ShippingAddress;
if (contact == null)
{
contact = user.BillingAddress;
}
}
To:
Address contact = user.ContactAddress ??
order.ShippingAddress ??
user.BillingAddress;
相反,我认为以下是正确的(如果我错了,请纠正我)
Address contact = (user.ContactAddress ?? order.ShippingAddress) ??
user.BillingAddress;
该规范实际上在这一点上是自相矛盾的。
C# 4 规范第 7.13 节指出:
空合并运算符是右关联的,这意味着操作从右到左分组。例如,形式的表达式a ?? b ?? c
被评估为a ?? (b ?? c)
.
另一方面,正如已经指出的,7.3.1 声称:
除赋值运算符外,所有二元运算符都是左结合的
我完全同意,对于简单的情况,如何分组并不重要......但是有may如果操作数具有不同的类型,那么由于隐式类型转换会做一些有趣的事情,所以这确实很重要。
我将进一步考虑它,ping Mads 和 Eric,并为 C# in Depth 的相关部分添加勘误表(这激发了这个问题)。
编辑:好的,我现在有一个例子does很重要......并且空合并运算符绝对是right-关联,至少在 MS C# 4 编译器中。代码:
using System;
public struct Foo
{
public static implicit operator Bar(Foo input)
{
Console.WriteLine("Foo to Bar");
return new Bar();
}
public static implicit operator Baz(Foo input)
{
Console.WriteLine("Foo to Baz");
return new Baz();
}
}
public struct Bar
{
public static implicit operator Baz(Bar input)
{
Console.WriteLine("Bar to Baz");
return new Baz();
}
}
public struct Baz
{
}
class Test
{
static void Main()
{
Foo? x = new Foo();
Bar? y = new Bar();
Baz? z = new Baz();
Console.WriteLine("Unbracketed:");
Baz? a = x ?? y ?? z;
Console.WriteLine("Grouped to the left:");
Baz? b = (x ?? y) ?? z;
Console.WriteLine("Grouped to the right:");
Baz? c = x ?? (y ?? z);
}
}
Output:
Unbracketed:
Foo to Baz
Grouped to the left:
Foo to Bar
Foo to Bar
Bar to Baz
Grouped to the right:
Foo to Baz
换句话说,
x ?? y ?? z
行为相同
x ?? (y ?? z)
but not与
(x ?? y) ?? z
我目前不确定为什么会有two使用时从 Foo 到 Bar 的转换(x ?? y) ?? z
- 我需要更仔细地检查一下......
编辑:我现在有另一个问题 https://stackoverflow.com/questions/6256847覆盖双重转换...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)