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

问题描述 投票:15回答:5

在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#中做到这一点?

c# tuples iterable-unpacking decomposition
5个回答
15
投票

.NET中有一组Tuple类:

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

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

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

37
投票

从C#7开始,你可以安装System.ValueTuple

PM> Install-Package System.ValueTuple

然后你可以打包并打开ValueTuple

(int, int) MyMethod()
{
    return (row, col);
}

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

7
投票

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

public class Extensions
{
  public static void UnpackTo<T1, T2>(this Tuple<T1, T2> t, out T1 v1, out T2 v2)
  {
    v1 = t.Item1;
    v2 = t.Item2;
  }
}

Tuple<int, int> 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

1
投票

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

Tuple<int, int> MyMethod()
{
    return Tuple.Create(0, 1);
}

// Usage:
var myTuple = MyMethod();
var row = myTuple.Item1;  // value of 0
var col = myTuple.Item2;  // value of 1

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
© www.soinside.com 2019 - 2024. All rights reserved.