Discards,在 C#7 中可以在声明变量的任何地方使用,顾名思义,丢弃结果。因此可以在没有变量的情况下使用丢弃:
p.GetCoordinates(out var x, out _);
它可用于丢弃表达式结果:
_ = 42;
在示例中,
p.GetCoordinates(out var x, out _);
_ = 42;
没有变量,_
,正在介绍中。使用弃牌的情况只有两种。
然而,如果一个标识符_
存在于范围内,则无法使用 Discards:
var _ = 42;
_ = "hello"; // error - a string cannot explicitly convert from string to int
例外情况是当_
变量用作输出变量。在这种情况下,编译器会忽略类型或var
并将其视为丢弃:
if (p.GetCoordinates(out double x, out double _))
{
_ = "hello"; // works fine.
Console.WriteLine(_); // error: _ doesn't exist in this context.
}
请注意,只有在这种情况下,才会发生这种情况:out var _
or out double _
用来。只需使用out _
然后它被视为对现有变量的引用,_
,如果它在范围内,例如:
string _;
int.TryParse("1", out _); // complains _ is of the wrong type
最后,*
在围绕丢弃物的讨论早期就提出了这种符号,但被放弃了_因为后者是其他语言中更常用的表示法.