元组在 C# 中展开类似于 Python [英] Tuple unrolling in C# similar to Python

查看:37
本文介绍了元组在 C# 中展开类似于 Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,我们可以使用类似的语法展开元组:

In Python we can unroll a tuple with similar syntax:

a, b = (1, 2)

C# 中是否有类似的结构?或访问元素,如:

Is there are similar structure in C#? Or accessing elements like:

Tuple<int, int> t = Tuple.Create(1, 2);
Console.Write(t.Item1);

唯一可能的方法?

推荐答案

C# 语言不直接支持元组解构(有时称为爆炸"),即将其元素分布在多个变量上.

Tuple destructuring (sometimes called "explosion"), i.e. distributing its elements over several variables, is not directly supported by the C# language.

您可以编写自己的扩展方法:

You could write your own extension method(s):

static void ExplodeInto<TA,TB>(this Tuple<TA,TB> tuple, out TA a, out TB b)
{
    a = tuple.Item1;
    b = tuple.Item2;
}

var tuple = Tuple.Create(1, 2);
int a, b;
tuple.ExplodeInto(out a, out b);

上面的例子仅适用于成对(即具有两个项目的元组).您需要为每个 Tuple<> 大小/类型编写一个这样的扩展方法.

The above example is just for pairs (i.e. tuples with two items). You would need to write one such extension method per Tuple<> size/type.

在即将发布的 C# 语言版本中,您可能能够在表达式中声明变量.这可能使您能够将上面的最后两行代码组合成 tuple.ExplodeInto(out int a, out int b);.

更正:声明表达式显然已从 C# 6 的计划功能中删除,或者至少受到限制;结果,我上面的建议将不再有效.

这篇关于元组在 C# 中展开类似于 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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