奇怪的运营商precedence用? (空合并运算符) [英] Weird operator precedence with ?? (null coalescing operator)

查看:189
本文介绍了奇怪的运营商precedence用? (空合并运算符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我有一个奇怪的错误我在那里用串联的字符串 INT?并在那之后增加一个字符串。

Recently I had a weird bug where I was concatenating a string with an int? and then adding another string after that.

我的code基本上这是等效的:

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?

推荐答案

空合并经营者具有非常低的 precedence 所以你的code正在跨preTED为:

The null coalescing operator has very low precedence so your code is being interpreted as:

int? x = 10;
string s = ("foo" + x) ?? (0 + "bar");

在这个例子中,两个前pressions是字符串,因此编译,但你想要什么没有做。在你的下一个例子中, ?? 运算符的左侧是一个字符串,而右手边是一个整数,所以它不会编译:

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

这篇关于奇怪的运营商precedence用? (空合并运算符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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