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

jb.*_*jb. 19 c# tuples decomposition iterable-unpacking

在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
Run Code Online (Sandbox Code Playgroud)

但是在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
Run Code Online (Sandbox Code Playgroud)

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

Ela*_*zar 40

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

PM> Install-Package System.ValueTuple
Run Code Online (Sandbox Code Playgroud)

然后你可以打包和解压缩ValueTuple:

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

(int row, int col) = MyMethod();
// mylist[row][col]
Run Code Online (Sandbox Code Playgroud)


dtb*_*dtb 15

.NET中有一组Tuple类:

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

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

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

  • 因果阅读器的注意事项:`Tuple <...>`仅在.NET4 +中是标准的. (2认同)

f.c*_*ani 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
Run Code Online (Sandbox Code Playgroud)