C# 7 元组和 lambda [英] C# 7 tuples and lambdas

查看:28
本文介绍了C# 7 元组和 lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用新的 c# 7 元组语法,是否可以指定一个带有元组作为参数的 lambda,并在 lambda 中使用未打包的值?

With new c# 7 tuple syntax, is it possible to specify a lambda with a tuple as parameter and use unpacked values inside the lambda?

例子:

var list = new List<(int,int)>();

在 lambda 中使用元组的常规方法:

normal way to use a tuple in lambda:

list.Select(value => value.Item1*2 + value.Item2/2);

我希望一些新的糖可以避免 .Item1 .Item2,例如:

i expected some new sugar to avoid .Item1 .Item2, like:

list.Select((x,y) => x*2 + y/2);

最后一行不起作用,因为它被视为 lambda 的两个参数.我不确定是否有办法做到这一点.

The last line does not work because it is treated as two parameters for lambda. I am not sure if there is a way to do it actually.

我在 lambda 定义中尝试了双括号,但没有成功:((x,y)) =>...,也许尝试起来很愚蠢,但双括号实际上在这里工作:

I tried double parentesis in lambda definition and it didn't work: ((x,y)) => ..., and maybe it was stupid to try, but double parenthesis actually work here:

list.Add((1,2));

另外,我的问题不完全是关于避免丑陋的默认名称 .Item .Item2,而是关于在 lambda 中实际解包元组(也许是为什么它没有实现或不可能).如果您来这里是为了解决默认名称,请阅读 Sergey Berezovskiy 的回答.

Also, my question is not quite about avoiding ugly default names .Item .Item2, it is about actual unpacking a tuple in lambda (and maybe why it's not implemented or not possible). If you came here for a solution to default names, read Sergey Berezovskiy's answer.

编辑 2:

刚刚想到一个更一般的用例:是否可以(或为什么不)解构"传递给方法的元组?像这样:

Just thought of a more general use case: is it possible (or why not) to "deconstruct" tuple passed to a method? Like this:

void Foo((int,int)(x,y)) { x+y; }

而不是这个:

void Foo((int x,int y) value) { value.x+value.y }

推荐答案

如你所见,对于:

var list = new List<(int,int)>();

至少希望能够做到以下几点:

One would at least expect to be able to do the following:

list.Select((x,y) => x*2 + y/2);

但 C# 7 编译器(尚)不支持这一点.期望糖能够满足以下条件也是合理的:

But the C# 7 compiler doesn't (yet) support this. It is also reasonable to desire sugar that would allow the following:

void Foo(int x, int y) => ...

Foo(list[0]);

编译器将 Foo(list[0]); 自动转换为 Foo(list[0].Item1, list[0].Item2);.

with the compiler converting Foo(list[0]); to Foo(list[0].Item1, list[0].Item2); automatically.

这些目前都不可能.但是,提案:lambda 参数列表中的元组解构 问题存在于 dotnet/cshaplang GitHub 上的 repo,要求语言团队考虑这些功能以用于 C# 的未来版本.如果您也希望看到对此的支持,请务必将您的声音添加到该线程.

Neither of these is currently possible. However, the issue, Proposal: Tuple deconstruction in lambda argument list, exists on the dotnet/csharplang repo on GitHub, requesting that the language team consider these features for a future version of C#. Please do add your voices to that thread if you too would like to see support for this.

这篇关于C# 7 元组和 lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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