奇怪的运算符优先级 ??(空合并运算符) [英] Weird operator precedence with ?? (null coalescing operator)
问题描述
最近我遇到了一个奇怪的错误,我将一个字符串与一个 int?
连接起来,然后在此之后添加另一个字符串.
Recently I had a weird bug where I was concatenating a string with an int?
and then adding another string after that.
我的代码基本上是这样的:
My code was basically the equivalent of this:
int? x=10;
string s = "foo" + x ?? 0 + "bar";
令人惊讶的是,这将在没有警告或不兼容的类型错误的情况下运行和编译,就像这样:
Amazingly enough this will run and compile without warnings or incompatible type errors, as will this:
int? x=10;
string s = "foo" + x ?? "0" + "bar";
然后这会导致意外的类型不兼容错误:
And then this results in an unexpected type incompatibility error:
int? x=10;
string s = "foo" + x ?? 0 + 12;
这个更简单的例子也一样:
As will this simpler example:
int? x=10;
string s = "foo" + x ?? 0;
有人可以向我解释一下这是如何工作的吗?
Can someone explain how this works to me?
推荐答案
空合并运算符具有非常低的 优先级 所以你的代码被解释为:
The null coalescing operator has very low precedence so your code is being interpreted as:
int? x = 10;
string s = ("foo" + x) ?? (0 + "bar");
在这个例子中,两个表达式都是字符串,所以它可以编译,但不会做你想要的.在您的下一个示例中,??
运算符的左侧是一个字符串,但右侧是一个整数,因此无法编译:
In this example both expressions are strings so it compiles, but doesn't do what you want. In your next example the left side of the ??
operator is a string, but the right hand side is an integer so it doesn't compile:
int? x = 10;
string s = ("foo" + x) ?? (0 + 12);
// Error: Operator '??' cannot be applied to operands of type 'string' and 'int'
解决办法当然是加括号:
The solution of course is to add parentheses:
int? x = 10;
string s = "foo" + (x ?? 0) + "bar";
这篇关于奇怪的运算符优先级 ??(空合并运算符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!