C#7 : Underscore ( _ ) & Star ( * ) in Out variable

标签 c# c#-7.0

我正在阅读 C#7 中新的输出变量功能 here .我有两个问题:

  1. 它说

    We allow "discards" as out parameters as well, in the form of a _, to let you ignore out parameters you don’t care about:

    p.GetCoordinates(out var x, out _); // I only care about x
    

    问:我想这只是一个信息,而不是 C#7 的新功能,因为我们也可以在 C#7.0 之前的版本中这样做:

    var _;
    if (Int.TryParse(str, out _))
    ...
    

    还是我在这里遗漏了什么?

  2. 当我按照同一博客中提到的那样操作时,我的代码会出错:

    ~Person() => names.TryRemove(id, out *);
    

    * 不是有效的标识符。我猜是 Mads Torgersen 的疏忽?

最佳答案

Discards , 在 C#7 中可以在声明变量的任何地方使用,以 - 顾名思义 - 丢弃结果。所以丢弃可以与 out 变量一起使用:

p.GetCoordinates(out var x, out _);

它可以用来丢弃表达式结果:

_ = 42;

在例子中,

p.GetCoordinates(out var x, out _);
_ = 42;

没有引入变量_。只有两种情况使用了丢弃。

但是,如果范围内存在标识符 _,则不能使用丢弃:

var _ = 42;
_ = "hello"; // error - a string cannot explicitly convert from string to int

异常(exception)情况是 _ 变量用作输出变量。在这种情况下,编译器忽略类型或 var 并将其视为丢弃:

if (p.GetCoordinates(out double x, out double _))
{
    _ = "hello"; // works fine.
    Console.WriteLine(_); // error: _ doesn't exist in this context.
}

请注意,只有在这种情况下使用 out var _out double _ 时才会发生这种情况。只需使用 out _ 然后它被视为对现有变量 _ 的引用,如果它在范围内,例如:

string _;
int.TryParse("1", out _); // complains _ is of the wrong type

最后,* 符号是在围绕丢弃的讨论早期提出的,but was abandoned in favour of _ due to the latter being a more commonly used notation in other languages .

关于C#7 : Underscore ( _ ) & Star ( * ) in Out variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42920622/

相关文章:

c# - 如何在 C# 中安全地将 System.Object 转换为 `bool`?

c# - 如何声明 C# 记录类型?

c# - C# 7 中的 C# 匿名类型是否多余

c# - 如何使用 C# 从 SQL 数据库获取值到文本框?

c# - 尽管有 Distinct(),LINQ 查询仍返回重复项

c# - 如何从 XAML 中的文本框中获取值?

c# - 在 Visual Studio 2008 中打破长代码行

c# - 我应该等待 ValueTask<T> 吗?

visual-studio-2017 - VS "15"Preview 中提供了 C# 7.0 的哪些功能?