C# 语言参考<!---->
ref(C# 参考)<!---->
<!--Content type: DocStudio. Transform: devdiv2mtps.xslt.-->
ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。若要使用 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
}
}
传递到 ref 参数的参数必须最先初始化。这与 out 不同,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(ref int i) { }
public void SampleMethod(out int i) { }
}
但是,如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两类参数,则可以进行重载,如下所示:
class RefOutOverloadExample
{
public void SampleMethod(int i) { }
public void SampleMethod(ref int i) { }
}
<script type="text/Javascript"> var ExpCollDivStr = ExpCollDivStr; ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl12bccfc0c,"; var ExpCollImgStr = ExpCollImgStr; ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl12img,"; </script>
备注
备注
<script type="text/Javascript"> var ExpCollDivStr = ExpCollDivStr; ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl143faeb7d,"; var ExpCollImgStr = ExpCollImgStr; ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl14img,"; </script>
示例
复制代码
示例
按引用传递值类型(如上所示)是有用的,但是 ref 对于传递引用类型也是很有用的。这允许被调用的方法修改该引用所引用的对象,因为引用本身是按引用来传递的。下面的示例显示出当引用类型作为 ref 参数传递时,可以更改对象本身。
class RefRefExample
{
static void Method(ref string s)
{
s = "changed";
}
static void Main()
{
string str = "original";
Method(ref str);
// str is now "changed"
}
}
C# ref 关键字详解
5920

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



