{
int temp = x;
x = y;
y = temp;
}
调用该方法时,请在调用中使用 ref 关键字,如下所示:
SwapByRef (ref i, ref j);
传递引用类型参数
引用类型的变量不直接包含其数据;它包含的是对其数据的引用。当通过值传递引用类型的参数时,有可能更改引用所指向的数据,如某类成员的值。但是无法更改引用本身的值;也就是说,不能使用相同的引用为新类分配内存并使之在块外保持。若要这样做,请使用 ref(或 out)关键字传递参数。为了简单起见,以下示例使用 ref。
示例 4:通过值传递引用类型
下面的示例演示通过值向 Change 方法传递引用类型的参数 myArray。由于该参数是对 myArray 的引用,所以有可能更改数组元素的值。但是,试图将参数重新分配到不同的内存位置时,该操作仅在方法内有效,并不影响原始变量 myArray。
// PassingParams4.cs
// Passing an array to a method without the ref keyword.
// Compare the results to those of Example 5.
using System;
class PassingRefByVal
{
static void Change(int[] arr)
{
arr[0]=888; // This change affects the original element.
arr = new int[5] {-3, -1, -2, -3, -4}; // This change is local.
Console.WriteLine("Inside the method, the first element is: {0}", arr[0]);
}
public static void Main()
{
int[] myArray = {1,4,5};
Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", myArray [0]);
Change(myArray);
Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", myArray [0]);
}
}
输出
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
代码讨论
在上个示例中,数组 myArray 为引用类型,在未使用 ref 参数的情况下传递给方法。在此情况下,将向方法传递指向 myArray 的引用的一个副本。输出显示方法有可能更改数组元素的内容(从 1 改为 888)。但是,在 Change 方法内使用 new 运算符分配新的内存部分,将使变量 arr 引用新的数组。因此,这之后的任何更改都不会影响原始数组 myArray(它是在 Main 内创建的)。实际上,本示例中创建了两个数组,一个在 Main 内,一个在 Change 方法内。
示例 5:通过引用传递引用类型
本示例除在方法头和调用中使用 ref 关键字以外,其余与“示例 4”相同。方法内发生的任何更改都会影响调用程序中的原始变量。
// PassingParams5.cs
// Passing an array to a method with the ref keyword.
// Compare the results to those of Example 4.
using System;
class PassingRefByRef
{
static void Change(ref int[] arr)
{
// Both of the following changes will affect the original variables:
arr[0]=888;
arr = new int[5] {-3, -1, -2, -3, -4};
Console.WriteLine("Inside the method, the first element is: {0}", arr[0]);
}
public static void Main()
{
int[] myArray = {1,4,5};
Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", myArray [0]);
Change(ref myArray);
Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", myArray [0]);
}
}
输出
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 fi
| 对此文章发表了评论 |

