Linqpad 使用丢弃(_ = 下划线)抛出错误 CS0246 - 找不到类型或名称空间名称“_”

Linqpad use of discard (_ = underscore) throws Error CS0246 - the type or namespace name '_' could not be found

我想了解命名元组和丢弃。

基于C# 7.0: Tuples Explained (msdn-magazine 2017-08)我创建了这个程序

void Main()
{

(string firstname, _, int age) user = ("surfmuggle", "discard this", 15);
user.Dump();
}

但它抛出

CS0246 The type or namespace name '_' could not be found (press F4 to add a using directive or assembly reference)

问题

谢谢

程序的屏幕

这与 LINQPad 无关 - 您将在 Visual Studio 中遇到相同的错误。

问题是您试图在不受支持的上下文中使用 C# 的丢弃项。来自文档:

In C# 7.0, discards are supported in assignments in the following contexts:

  • Tuple and object deconstruction.
  • Pattern matching with is and switch.
  • Calls to methods with out parameters.
  • A standalone _ when no _ is in scope.

您的示例适用于解构上下文:

(string firstname, _, int age) = ("surfmuggle", "discard this", 15);
firstname.Dump();
age.Dump();