1. ref 和out 关键字会导致参数通过引用来传递,不同之处在于ref 要求变量必须在传递之前进行初始化,而out 参数传递的变量不必在传递之前进行初始化,但被调用的方法需要在返回之前赋一个值。 若要使用ref 和out 参数,方法定义和调用方法都必须显式使用 ref 和 out 关键字。
class Example
{
static void Method1(ref int i)
{
i = 5;
}
static void Method2(out int i)
{
i = 15;
}
static void Main()
{
int val1 = 0;
Method1(ref val1);
// val1 is now 5
int val2;
Method2(out val2);
// val2 is now 15
}
}
2. 尽管 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; }
}
3. 属性不是变量,它们实际上是方法,因此不能作为 out 参数传递。
4. 当希望方法返回多个值时,声明ref 和 out 参数很有用。

浙公网安备 33010602011771号