在 C# 中用括号括起来的整数?

Viv*_*Dev 0 c#

我已经使用 C# 多年了,今天我很困惑地看到以下代码。

int whatIsThis = (0);
Run Code Online (Sandbox Code Playgroud)

这是什么意思?

我已经在网上搜索过,但到目前为止还没有运气。

Dai*_*Dai 13

这种情况下的括号完全是多余的。这些语句在语义上都是相同的:

int whatIsThis = 0;
int whatIsThis = (0);
int whatIsThis = ((0));
int whatIsThis = (((0))); // etc
Run Code Online (Sandbox Code Playgroud)

也就是说,在 C# 中,当您指定负整数文字时,有时确实需要使用括号以避免与一元运算-符和二元运算符产生歧义。有可能这段代码之前使用了否定文字,而作者在将其更改为使用零时没有删除括号。


Stu*_*tLC 5

作者可能一直在学习value tuples,尽管 的变量类型int似乎另有说明。

即使作者曾经var推断类型,元组构造的括号简写也不适用于 0 或 1 元组 - 分配的类型仍然是标量 int,文字 0 周围的括号是多余的,如根据其他答案。

var i = (0); // i is still an int (scalar primitive), not a value tuple
Run Code Online (Sandbox Code Playgroud)

为了创建 1 元组,您需要使用显式构造函数或工厂方法来执行此操作:

var t1 = new ValueTuple<int>(0);
var t2 = ValueTuple.Create(5);
Run Code Online (Sandbox Code Playgroud)

但对于 2 元组及以上,括号简写将适用:

var t3 = (5, 3);
// access t3.Item1, t3.Item2
Run Code Online (Sandbox Code Playgroud)

同样,解构对 1 元组不起作用:

var (a) = (5); // No deconstruct method with 1 out parameters found for int.
Run Code Online (Sandbox Code Playgroud)

解构仅适用于 2 元组及以上:

var (a, b) = (5, 3);
Run Code Online (Sandbox Code Playgroud)