MSDN:关于C#引用

MSDN:关于C#引用

引用类型的变量不直接包含其数据;它包含的是对其数据的引用。当通过值传递引用类型的参数时,有可能更改引用所指向的数据,如某类成员的值。但是无法更改引用本身的值;也就是说,不能使用相同的引用为新类分配内存并使之在块外保持。若要这样做,应使用 ref out 关键字传递参数。为了简单起见,下面的示例使用 ref。

示例:通过值传递引用类型

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]);

    }

}

在上个示例中,数组 arr 为引用类型,在未使用 ref 参数的情况下传递给方法。在此情况下,将向方法传递指向 arr 的引用的一个副本。输出显示方法有可能更改数组元素的内容,在这种情况下,从 1 改为 888。但是,在 Change 方法内使用 new 运算符来分配新的内存部分,将使变量 pArray 引用新的数组。因此,这之后的任何更改都不会影响原始数组 arr(它是在 Main 内创建的)。实际上,本示例中创建了两个数组,一个在 Main 内,一个在 Change 方法内。

posted @ 2010-06-01 08:52  gege_s  Views(561)  Comments(0)    收藏  举报