传递参数有ref和out二种:
区别:
out 关键字会导致参数通过引用来传递。这与ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。
若要使用 out 参数,方法定义和调用方法都必须显式使用out 关键字。
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) { }
}
用法,例:
class OutExample
{
static void Method(out int i)
{ i = 44; }
static void Main()
{
int value;
Method(out value); // value is now 44
}
}
本文详细介绍了C#中ref和out关键字的区别及其用法。重点解释了这两种关键字如何影响参数传递,并提供了具体的代码示例来展示它们的运作机制。

被折叠的 条评论
为什么被折叠?



