1.ref 关键字使参数按引用传递。
2.若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。例如:
class RefExample { static void Method(ref int i) { i = 44; } static void Main() { int val = 0; Method(ref val); // val is now 44 } }
3.传递到 ref 参数的参数必须最先初始化。这与 out 不同,out 的参数在传递之前不需要显式初始化。
4.尽管 ref 和 out 在运行时的处理方式不同,但它们在编译时的处理方式是相同的。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。
例如:
从编译的角度来看,以下代码中的两个方法是完全相同的,因此将不会编译以下代码:
class CS0663_Example { // compiler error CS0663: "cannot define overloaded // methods that differ only on ref and out" public void SampleMethod(ref int i) { } public void SampleMethod(out int i) { } }
class RefOutOverloadExample { public void SampleMethod(int i) { } public void SampleMethod(ref int i) { } }