奇怪的运算符优先级与?? (null合并运算符)

Ear*_*rlz 22 c# types null-coalescing-operator

最近我有一个奇怪的错误,我在那里连接一个字符串int?然后添加另一个字符串.

我的代码基本上相当于:

int? x=10;
string s = "foo" + x ?? 0 + "bar";
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,这将运行和编译没有警告或不兼容的类型错误,这将是:

int? x=10;
string s = "foo" + x ?? "0" + "bar";
Run Code Online (Sandbox Code Playgroud)

然后这会导致意外的类型不兼容错误:

int? x=10;
string s = "foo" + x ?? 0 + 12;
Run Code Online (Sandbox Code Playgroud)

这个更简单的例子也是如此:

int? x=10;
string s = "foo" + x ?? 0;
Run Code Online (Sandbox Code Playgroud)

有人能解释一下这对我有用吗?

Mar*_*ers 26

空合并运算符的优先级非常低,因此您的代码被解释为:

int? x = 10;
string s = ("foo" + x) ?? (0 + "bar");
Run Code Online (Sandbox Code Playgroud)

在这个例子中,两个表达式都是字符串,所以它编译,但不能做你想要的.在下一个示例中,??运算符的左侧是一个字符串,但右侧是一个整数,因此它不能编译:

int? x = 10;
string s = ("foo" + x) ?? (0 + 12);
// Error: Operator '??' cannot be applied to operands of type 'string' and 'int'
Run Code Online (Sandbox Code Playgroud)

解决方案当然是添加括号:

int? x = 10;
string s = "foo" + (x ?? 0) + "bar";
Run Code Online (Sandbox Code Playgroud)


Guf*_*ffa 11

??经营者具有较低的优先级+运营商,所以你的表现真的作品为:

string s = ("foo" + x) ?? (0 + "bar");
Run Code Online (Sandbox Code Playgroud)

首先,字符串"foo"和字符串值x是连接的,如果它是null(它不能),则串联字符串值0和字符串"bar".