相关疑难解决方法(0)

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

最近我有一个奇怪的错误,我在那里连接一个字符串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)

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

c# types null-coalescing-operator

22
推荐指数
2
解决办法
2502
查看次数

标签 统计

c# ×1

null-coalescing-operator ×1

types ×1