class Program
    {
        static void Main(string[] args)
        {
            Test a = new Test(3);
            Test b = new Test(4);
            Console.WriteLine(a.i.ToString());
            Console.WriteLine(b.i.ToString());
            Console.WriteLine("变换后");
            Swap(a, b);
            Console.WriteLine(a.i.ToString());
            Console.WriteLine(b.i.ToString());
            Console.Read();
        }
//下面的方法既然传入的是引用类型为什么不能达到交换的目的呢?

        public static void Swap(Test a, Test b)
        {            Test temp = null;
            temp = a;
            a = b;
            b = temp;
        }
        public static void Change(Test a)
        {
            a.i = 8888;
        }
    }
    public class Test{        public int i;
        public Test(int x)
        {
            i = x;
        }    }
//上面的结果显然没有达到交换的目的.那么下面的程序又是怎样呢?class Program
    {
        static void Main(string[] args)
        {
            Test a = new Test(3);
           
            Change(a);
            Console.WriteLine(a.i.ToString());
            Console.Read();
        }
        public static void Swap(Test a, Test b)
        {            Test temp = null;
            temp = a;
            a = b;
            b = temp;
        }
        public static void Change(Test a)
        {
            a.i = 8888;
        }
    }
    public class Test{        public int i;
        public Test(int x)
        {
            i = x;
        }    }
//结果为8888,又是为什么呢?
//再看看下面,这结果我想你已经知道了,但上面的两个问题答案又是什么呢?
class Program
    {
        static void Main(string[] args)
        {
            string str = "123";
            Change(str);
            Console.WriteLine(str);
            Console.Read();
        }
       
        public static void Change(string str)
        {
            str += "添加的数据";
        }
    }

解决方案 »

  1.   

                Test temp = null; 
                temp = a;  这里a和temp指向同一个内存地址
                a = b;     a修改了,那么temp和a指向是一致,temp也变成了b
                b = temp; 
      

  2.   

    2楼的回答出了问题,好了,还是我自己来揭帖算了.当一个引用对象作为参数传给一个方法时,也是将它的一个引用的拷贝(同样是指向哪一个实例的堆空间上的)传给方法的,所以对这个引用的拷贝的操作就可以对实际实例的堆空间进行操作,这也是
    public static void Change(Test a)
            {
                a.i = 8888;
            } 
    给a所指代的实例堆空间上的对象进行了操作缘故,最后结果就成了8888而当用
    public static void Swap(Test a, Test b)
            {            Test temp = null;
                temp = a;
                a = b;
                b = temp;
            } 
    时,传入给方法的a,b这俩个引用拷贝的改变实在给不了原来的的a,b.所以a,b并没有达到交换的目的.但我们用public static void Swap(ref Test a, ref Test b)
            {            Test temp = null;
                temp = a;
                a = b;
                b = temp;
            } 
    时,显然传入的就是对真正的a,b引用了,而非a,b引用的拷贝了,所以达到了交换a,b的目的.楼上明白了否,支持我的就拍掌哈.
    呵呵