当前位置:编程学习 > C#/ASP.NET >>

恳请高手指点,问题在代码里面已经注明了

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace chapter8_3
{
    class refswap {
        int a, b;
        public refswap(int i, int j)
        {
            a = i;
            b = j;
        }
        public void show (){
            Console.WriteLine("a:{0},b:{1}", a, b);
        }
        public void swap( ref refswap ob1, ref refswap ob2) {
            refswap t;
            t = ob1;
            ob1 = ob2;
            ob2 = t; /*就是这个红色的部分明明已经把两个对象的引用调换了,照理说实参也会跟着一起换的啊,因为是把实参的引用传递过来了啊,可是为什么还要用ref呢*/        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            refswap x = new refswap(1, 2);
            refswap y = new refswap(3, 4);
            Console.WriteLine("改变前的x");
            x.show();
            Console.WriteLine("改变前的y");
            y.show();
            x.swap( ref x,ref y);
            Console.WriteLine("改变后的x");    
            x.show();
            Console.WriteLine("改变后的y");
                y.show();
                Console.ReadLine();
           
        }
    }
} --------------------编程问答-------------------- 下面有2个Test方法,一个带引用,一个不带,分别都是实现为入参赋值,lz请分别用这两个Test方法试一下就知道为什么要加引用了。请参考MessageBox.Show出来的结果。



        private void button1_Click(object sender, EventArgs e)
        {
            int a = 0;
            int b = 0;

            Test(ref a, ref b);
            //Test(ref a, ref b);  // lz请分别用这两个Test方法试一下就知道了。

            MessageBox.Show(string.Format("{0}    {1}", a, b));
            
        }


        private void Test(int a, int b)
        {
            a = 1;
            b = 2;
        }

        private void Test(ref int a, ref int b)
        {
            a = 1;
            b = 2;
        }
--------------------编程问答-------------------- 上面的注释部分有点笔误,不过应该不影响理解,是:


           Test(ref a, ref b);
            //Test(a, b);  // lz请分别用这两个Test方法试一下就知道了。

补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,