ref 和 out 的区别
来源:互联网 发布:商场销售数据报表 编辑:程序博客网 时间:2024/05/21 19:04
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 的参数在传递之前不需要显式初始化。
尽管 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) { }}
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 参数传递的变量不需要在传递之前进行初始化,但需要调用方法以便在方法返回之前赋值。
- ref和out的区别
- ref 和 out 的区别
- out和ref的区别
- ref和out的区别
- ref和out的区别
- ref和out的区别
- ref 和 out 的区别
- Ref和Out的区别
- out和ref的区别?
- ref和out的区别
- out和ref的区别
- ref 和out的区别
- ref和out的区别
- ref和out的区别
- ref和out的区别
- ref和out的区别
- ref和out的区别
- ref和out的区别
- lambda表达式
- Android和Android Linux kernel源码获取
- 在Visual Studio 2010中使用Visual Leak Detector
- 常见的问题
- 为VirtualBox虚拟的Ubuntu加上远程SSH功能
- ref 和 out 的区别
- 如何给grub启动选项加入rootdelay
- Android Activity 和 Task 设计指导
- Python标准异常
- 博客第一篇:以后准备记录面试相关资料
- linux基础之ubuntu 10.04下的配置tftp服务器(修改)
- 2、Ecshop上传商品图片不清晰
- Java线程之线程同步
- wince槛外人窥探--存储布局