交换两个数的位置,要求用10种方法

 第一种:(int a=3,b=5;)

设置一个变量temp

第二种:不设置变量

a=a+b;..........a=8

b=a-b;...........b=3

a=a-b;...........a=5

第三种:out关键字的做法

class Program
    {
        public void TestOut(int a,int b,out int m,out int n) 
        {
            m = b;
            n = a;
        }
        static void Main(string[] args)
        {
            int a = 3, b = 5;
            Program p = new Program();
            p.TestOut(a,b,out a,out b);
            Console.WriteLine("a="+a);
            Console.WriteLine("b="+b);
            Console.ReadLine();
        }
    }

 

说明:

1.out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于ref 要求变量必须在传递之前进行初始化。

2.方法定义和调用方法都必须显式使用 out 关键字。

3.属性不是变量,因此不能作为 out 参数传递。

4.示例

class Program
    {
        //使用out后必须对变量赋值   
        public void TestOut(out int x, out int y)
        {
            x = 1;
            y = 2;
        }
        //此时传进来的值分别为x1:10,y1:11,输出之后的x1的值为2   

        public void TestRef(ref int x, ref int y)
        {
            //引用剪剪那句话传进来的是猪,出来的可能是头牛(很精辟!)   
            x = 2;

        }
        static void Main(string[] args)
        {
            int x;
            int y;
            Program P1 = new Program();
            P1.TestOut(out x, out y);
            Console.WriteLine("x={0},y={1}", x, y);
            //在使用之前ref必须对变量赋值   
            int x1 = 10;
            int Y1 = 11;
            P1.TestRef(ref x1, ref Y1);
            Console.WriteLine("x1={0},y1={1}", x1, Y1);
            Console.ReadLine();
        }
    }  

第四种:

//Stack<int> st = new Stack<int>();//栈,带尖括号的是泛型,只接受括号里的类型
//st.Push(a);//入栈
//st.Push(b);

//a = st.Pop();//出栈,利用栈的先入后出先出来b的值赋给a
//b = st.Pop();//后出来a的值赋给b

第五种:

//Queue<int> q = new Queue<int>();//队列
//q.Enqueue(a);//入队列
//q.Enqueue(b);

//b = q.Dequeue();//出队列,利用先入先出
//a = q.Dequeue();

以上列出5种方法,还有list等方法。。。。。

posted @ 2016-08-09 17:34  云晴  阅读(1008)  评论(0编辑  收藏  举报