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

查看:128
本文介绍了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参数列表中的元组解构,存在于<$ GitHub上的c $ c> dotnet / csharplang 仓库,要求语言团队考虑将这些功能用于将来的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天全站免登陆