我想同时为多个变量赋值。我知道它在 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)
这是有效的 C#,使用 C# 7 中引入的元组:
int (a, b) = (1, 2);
(a, b) = (b, a + b);
我不会说这是惯用的 C#——我从未在野外见过它,而且我认为没有多少人知道你可以做到这一点——但它是有效的。
编译器实际上并不使用 ValueTuple 类来执行此操作 - 它综合了以下代码:
int a = 1;
int b = 2;
int temp1 = b;
int temp2 = a + b;
a = temp1;
b = temp2;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句