REF关键字
ref 关键字会导致通过引用传递的参数,而不是值。 通过引用传递的效果是在方法中对参数的任何改变都会反映在调用方的基础参数中。 引用参数的值与基础参数变量的值始终是一样的。
不要将“通过引用传递”概念与“引用类型”概念相混淆。 这两个概念不同。 方法参数无论是值类型还是引用类型,都可通过 ref 进行修饰。 通过引用传递值类型时没有值类型装箱。
若要使用 ref 参数,方法定义和调用的方法必须显式使用关键字,ref。 例如:
class RefExample { static void Method(ref int i) { // Rest the mouse pointer over i to verify that it is an int. // The following statement would cause a compiler error if i // were boxed as an object. i = i + 44; } static void Main() { int val = 1; Method(ref val); Console.WriteLine(val); // Output: 45 } }
OUT关键字
out 关键字会导致参数通过引用来传递。 这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。
若要使用 out 参数,方法定义和调用方法都必须显式使用 out 关键字。 例如:
class OutExample { static void Method(out int i) { i = 44; } static void Main() { int value; Method(out value); // value is now 44 } }
尽管作为 out 参数传递的变量不必在传递之前进行初始化,但被调用的方法需要在返回之前赋一个值。
OUT与REF同时使用
尽管 ref 和 out 关键字会导致不同的运行时行为,但在编译时并不会将它们视为方法签名的一部分。 因此,如果两个方法唯一的区别是:一个接受 ref 参数,另一个接受 out 参数,则无法重载这两个方法。 例如,不会编译下面的代码:
class CS0663_Example { // Compiler error CS0663: "Cannot define overloaded // methods that differ only on ref and out". public void SampleMethod(out int i) { } public void SampleMethod(ref int i) { } }
但是,如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两类参数,则可以进行重载,如下所示:
class OutOverloadExample { public void SampleMethod(int i) { } public void SampleMethod(out int i) { i = 5; } }
属性不是变量,因此不能作为 out 参数传递。
有关传递数组的信息,请参见使用 ref 和 out 传递数组(C# 编程指南)。
不能为以下方法使用 ref 和 out 关键字: