C#中的元组和解包分配支持?

在Python中我可以写

def myMethod(): #some work to find the row and col return (row, col) row, col = myMethod() mylist[row][col] # do work on this element 

但是在C#中,我发现自己在写作

 int[] MyMethod() { // some work to find row and col return new int[] { row, col } } int[] coords = MyMethod(); mylist[coords[0]][coords[1]] //do work on this element 

Pythonic方式显然更加清洁。 有没有办法在C#中做到这一点?

.NET中有一组Tuple类:

 Tuple MyMethod() { // some work to find row and col return Tuple.Create(row, col); } 

但是没有像在Python中那样解压缩它们的紧凑语法:

 Tuple coords = MyMethod(); mylist[coords.Item1][coords.Item2] //do work on this element 

从C#7开始,您可以使用ValueTuple :

 Install-Package System.ValueTuple 

然后你可以打包ValueTuples压缩ValueTuples

 (int, int) MyMethod() { return (row, col); } (int row, int col) = MyMethod(); // mylist[row][col] 

扩展可能会更接近Python元组解包,效率更高但更易读(和Pythonic):

 public class Extensions { public static void UnpackTo(this Tuple t, out T1 v1, out T2 v2) { v1 = t.Item1; v2 = t.Item2; } } Tuple MyMethod() { // some work to find row and col return Tuple.Create(row, col); } int row, col; MyMethod().UnpackTo(out row, out col); mylist[row][col]; // do work on this element 

C#是一种强类型语言,其类型系统强制执行一个规则,该函数可以具有none( void )或1返回值。 C#4.0引入了Tuple类:

 Tuple MyMethod() { return Tuple.Create(0, 1); } // Usage: var myTuple = MyMethod(); var row = myTuple.Item1; // value of 0 var col = myTuple.Item2; // value of 1 

这是一个带有值解包的zip示例。 这里zip返回元组上的迭代器。

 int[] numbers = {1, 2, 3, 4}; string[] words = {"one", "two", "three"}; foreach ((var n, var w) in numbers.Zip(words, Tuple.Create)) { Console.WriteLine("{0} -> {1}", n, w); } 

输出:

 1 -> one 2 -> two 3 -> three