我希望能够在C#中不使用临时变量的情况下交换两个变量。这可以做到吗?
decimal startAngle = Convert.ToDecimal(159.9);
decimal stopAngle = Convert.ToDecimal(355.87);
// Swap each:
// startAngle becomes: 355.87
// stopAngle becomes: 159.9
发布于 2009-04-29 23:31:01
可以,请使用以下代码:
stopAngle = Convert.ToDecimal(159.9);
startAngle = Convert.ToDecimal(355.87);
对于任意值,这个问题就更难了。:-)
发布于 2009-12-29 15:34:49
int a = 4, b = 6;
a ^= b ^= a ^= b;
适用于所有类型,包括字符串和浮点数。
发布于 2013-03-06 02:17:23
BenAlabaster展示了一种进行变量切换的实用方法,但不需要try-catch子句。这段代码就足够了。
static void Swap<T>(ref T x, ref T y)
{
T t = y;
y = x;
x = t;
}
用法如图所示:
float startAngle = 159.9F
float stopAngle = 355.87F
Swap(ref startAngle, ref stopAngle);
您还可以使用扩展方法:
static class SwapExtension
{
public static T Swap<T>(this T x, ref T y)
{
T t = y;
y = x;
return t;
}
}
像这样使用它:
float startAngle = 159.9F;
float stopAngle = 355.87F;
startAngle = startAngle.Swap(ref stopAngle);
这两种方法都在方法中使用临时变量,但在进行交换时不需要临时变量。
https://stackoverflow.com/questions/804706
复制相似问题