前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#交换两个变量值的几种方法总结分享

C#交换两个变量值的几种方法总结分享

原创
作者头像
用户7718188
发布2022-11-06 20:10:15
6020
发布2022-11-06 20:10:15
举报
文章被收录于专栏:高级工程司高级工程司

使用临时变量实现

1

static void Main(string[] args){    int x = 1;    int y = 2;    Console.WriteLine("x={0},y={1}",x, y);    int temp = x;    x = y;    y = temp;    Console.WriteLine("x={0},y={1}", x, y);    Console.ReadKey();}

使用加减法实现

试想, 1+2=3,我们得到了两数相加的结果3。3-2=1,把1赋值给y,y就等于1; 3-1=2,把2赋值给x,这就完成了交换。

2

static void Main(string[] args){    int x = 1;    int y = 2;    Console.WriteLine("x={0},y={1}",x, y);    x = x + y; //x = 3    y = x - y; //y = 1    x = x - y; //x = 2     Console.WriteLine("x={0},y={1}", x, y);    Console.ReadKey();}

使用ref和泛型方法实现

如果把交换int类型变量值的算法封装到方法中,需要用到ref关键字。

3

static void Main(string[] args){    int x = 1;    int y = 2;    Console.WriteLine("x={0},y={1}",x, y);    Swap(ref x, ref  y);    Console.WriteLine("x={0},y={1}", x, y);    Console.ReadKey();}static void Swap(ref int x, ref int y){    int temp = x;    x = y;    y = x;}

如果交换string类型的变量值,就要写一个Swap方法的重载,让其接收string类型:

4

static void Main(string[] args){    string x = "hello";    string y = "world";    Console.WriteLine("x={0},y={1}",x, y);    Swap(ref x, ref  y);    Console.WriteLine("x={0},y={1}", x, y);    Console.ReadKey();}static void Swap(ref int x, ref int y){    int temp = x;    x = y;    y = x;}static void Swap(ref string x, ref string y){    string temp = x;    x = y;    y = x;}

如果交换其它类型的变量值呢?我们很容易想到通过泛型方法来实现,再写一个泛型重载。

5

static void Main(string[] args){    string x = "hello";    string y = "world";    Console.WriteLine("x={0},y={1}",x, y);    Swap<string>(ref x, ref y);    Console.WriteLine("x={0},y={1}", x, y);    Console.ReadKey();}static void Swap(ref int x, ref int y){    int temp = x;    x = y;    y = x;}static void Swap(ref string x, ref string y){    string temp = x;    x = y;    y = x;}static void Swap<T>(ref T x, ref T y){    T temp = x;    x = y;    y = temp;}

使用按位异或运算符实现

对于二进制数字来说,当两个数相异的时候就为1, 即0和1异或的结果是1, 0和0,以及1和1异或的结果是0。关于异或等位运算符的介绍

举例,把十进制的3和4转换成16位二进制分别是:

x = 0000000000000011;//对应十进制数字3 y = 0000000000000100; //对应十进制数字4

把x和y异或的结果赋值给x:x = x ^ y; x = 0000000000000111;

把y和现在的x异或,结果赋值给y:y = y ^ x y = 0000000000000011;

把现在的x和现在的y异或,结果赋值给x:x = x ^ y x = 0000000000000100;

按照上面的算法,可以写成如下:

6

static void Main(string[] args){    int x = 1;    int y = 2;    Console.WriteLine("x={0},y={1}",x, y);    x = x ^ y;    y = y ^ x;    x = x ^ y;    Console.WriteLine("x={0},y={1}", x, y);    Console.ReadKey();}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用临时变量实现
  • 使用加减法实现
  • 使用ref和泛型方法实现
  • 使用按位异或运算符实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档