首页 > 学院 > 开发设计 > 正文

C#交换两个变量值的多种写法

2019-11-17 02:25:04
字体:
来源:转载
供稿:网友

C#交换两个变量值的多种写法

在学习.Net/C#或者任何一门面向对象语言的初期,大家都写过交换两个变量值,通常是通过临时变量来实现。本篇使用多种方式实现两个变量值的交换。

假设int x =1; int y = 2;现在交换两个变量的值。

使用临时变量实现

        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,这就完成了交换。

        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关键字。

        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();
        }
<PRe style="font-size: 10px; font-family: consolas,'Courier New',courier,monospace; width:
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表