一叶知秋

Enjoy Every Day!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

   呵呵,这个标题太拗口,和绕口令差不多了。我们都知道向一个方法传递值类型参数时,按值传递和按引用传递参数是不同的。按值传递时只是传递参数的一个副本,方法内对参数对改变并不会影响原来的值。而按引用传递实际是把参数的地址传递到方法中,方法内对参数对改变会影响原来的值。而当参数是引用类型时会发生什么情况呢?引用类型作为参数本身就是传递其引用地址,所以按值传递引用类型并不会传送该参数的副本。而按引用传递引用类型时是传递其引用地址的引用。换句话说,按值传递引用类型时,可以修改该参数内的成员,并会影响原来的引用类型。但是如果为该参数创建了一个新的实例,那么并不会影响原来的引用类型。而引用传递时为该参数创建一个新的实例会影响原来的引用类型。

class PassingRefByVal
{
    static void Change(int[] pArray)
    {
        pArray[0] = 888;  // This change affects the original element.
        pArray = new int[5] {-3, -1, -2, -3, -4};   // This change is local.
        System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);
    }

    static void Main()
    {
        int[] arr = {1, 4, 5};
        System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr [0]);

        Change(arr);
        System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr [0]);
    }
}
//output:
//Inside Main, before calling the method, the first element is: 1
//Inside the method, the first element is: -3
//Inside Main, after calling the method, the first element is: 888


class PassingRefByRef
{
    static void Change(ref int[] pArray)
    {
        // Both of the following changes will affect the original variables:
        pArray[0] = 888;
        pArray = new int[5] {-3, -1, -2, -3, -4};
        System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);
    }
       
    static void Main()
    {
        int[] arr = {1, 4, 5};
        System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr[0]);

        Change(ref arr);
        System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr[0]);
    }
}
//output:
//Inside Main, before calling the method, the first element is: 1
//Inside the method, the first element is: -3
//Inside Main, after calling the method, the first element is: -3