c# - 在不使用另一个变量的情况下交换两个数字

标签 c#

<分区>

不使用临时变量交换两个变量 如果

int a=4; 
int b=3;

我需要交换这些变量并得到输出 a=3 和 b=4 无需在 C# 中使用另一个变量

最佳答案

使用Interlocked.Exchange()

int a = 4;
int b = 3;

b = Interlocked.Exchange(ref a, b);

告诉我更多

来自 MSDN:

Sets a 32-bit signed integer to a specified value as an atomic operation, and then returns the original value

编辑: 关于上面 Esoteric 的精细链接(谢谢),甚至还有一个 Interlocked.Exchange() for double 可能会有所帮助也有。

关于c# - 在不使用另一个变量的情况下交换两个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28207146/

相关文章:

c# - 如何使用 c# 在 Windows 8.1 中首次启动 App 时获取设备的当前位置?

c# - 使用 ImageList 图像

c# - 设置 ScrollBar 条的大小?

c# - Process.WaitForExit 挂起 - 但我只重定向标准输入?

c# - MVC3 注册表最佳实践

c# - 使用 C#,如何像 TinEye.com 在 Web 上那样在 Windows 文件系统中搜索图像?

c# - 通过 C# 复制 pdf 注释

c# - SetupSet 'forgets'方法设置的使用

c# - 在 C# 中以顺序方式使用 BinaryFormatter

c# - 无法在 asp .net 中使用相同的存储过程在同一页面上填充多个 DropDownList