C#7:下划线(_)&星号(*)输入Out变量 [英] C#7: Underscore ( _ ) & Star ( * ) in Out variable

查看:195
本文介绍了C#7:下划线(_)&星号(*)输入Out变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关C#7 此处。我有两个问题:

I was reading about new out variable features in C#7 here. I have two questions:


  1. 上面写着

  1. It says


我们也允许丢弃作为输出参数,以 _ 的形式,让您忽略不需要的参数:

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


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

Q: I guess this is just an info and not a new feature of C#7 because we can do so in pre C#7.0 too:

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

还是我在这里丢失了某些东西?

or am I missing something here?

当我按照同一博客所述进行操作时,我的代码给出了错误:

My code gives an error when I do as mentioned in same blog:

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

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

* is not a valid identifier. An oversight by Mads Torgersen I guess?


推荐答案

Discards 在C#7中可以在声明变量的任何地方使用,以-作为名称建议-丢弃结果。因此,可以将out与变量一起使用:

Discards, in C#7 can be used wherever a variable is declared, to - as the name suggests - discard the result. So a discard can be used with out variables:

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

它可用于丢弃表达式结果:

and it can be used to discard an expression result:

_ = 42;

在示例中,

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

没有变量 _ 被介绍。仅有两种情况使用了丢弃。

There is no variable, _, being introduced. There are just two cases of a discard being used.

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

If however, an identifier _ exists in the scope, then discards cannot be used:

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

code> _ 变量用作out变量。在这种情况下,编译器将忽略类型或 var 并将其视为丢弃:

The exception to this is when a _ variable is used as an out variable. In this case, the compiler ignores the type or var and treats it as a discard:

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 _ ,然后将其视为对现有变量 _ 的引用,如果它在范围内,例如:

Note that this only occurs if, in this case, out var _ or out double _ is used. Just use out _ and then it's treated as a reference to an existing variable, _, if it's in scope, eg:

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

最后, * 表示法是在有关丢弃物的讨论的早期提出的,但为了<$而放弃了。 c $ c> _ ,因为后者是其他语言中更常用的符号

Finally, the * notation was proposed early in the discussions around discards, but was abandoned in favour of _ due to the latter being a more commonly used notation in other languages.

这篇关于C#7:下划线(_)&amp;星号(*)输入Out变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆