我想同时为多个变量赋值.我知道它在python中如何工作但我需要一个C#的等价物.
我发现如果我想为新变量赋值,我可以这样做.
int a = 1 , b = 1;
//This works fine but now I need to set the variables again
a = b , b = a + b;
//But i can't do it like that
//I know that in python it would look like this (a , b = b , a+b)
Run Code Online (Sandbox Code Playgroud)
这是有效的C#,使用C#7中引入的元组:
int (a, b) = (1, 2);
(a, b) = (b, a + b);
Run Code Online (Sandbox Code Playgroud)
我不会说这是惯用的C# - 我从来没有在野外看过它,我认为很多人都不知道你能做到这一点 - 但它是有效的.
编译器实际上并不使用ValueTuple类来执行此操作 - 它合成以下代码:
int a = 1;
int b = 2;
int temp1 = b;
int temp2 = a + b;
a = temp1;
b = temp2;
Run Code Online (Sandbox Code Playgroud)