博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# Out,Ref 学习总结
阅读量:6872 次
发布时间:2019-06-26

本文共 932 字,大约阅读时间需要 3 分钟。

C# Out,Ref 学习总结。

  ref是传递参数的地址,out是返回值,两者有一定的相同之处,不过也有不同点。

  使用ref前必须对变量赋值,out不用。
  out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。 
  区别可以参看下面的代码:

public class OutRef
{
    static void outTest(out int x, out int y)
    {
        //离开这个函数前,必须对x和y赋值,否则会报错。
        //y = x;
        //上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行
        x = 1;
        y = 2;
    }
    static void refTest(ref int x, ref int y)
    {
        x = 1;
        y = x;
    }
    public static void OutRefTest()
    {
        //out test
        int a, b;
        //out使用前,变量可以不赋值
        outTest(out a, out b);
        String outMsg = String.Format("a is {0}, b is {1} ", a, b);
        int c = 11, d = 22;
        outTest(out c, out d);
        String outMsg2 = String.Format("a is {0}, b is {1} ", a, b);
 
        //ref test
        int m, n;
        //refTest(ref m, ref n);
        //上面这行会出错,ref使用前,变量必须赋值
 
        int o = 11, p = 22;
        refTest(ref o, ref p);
        String refMsg = String.Format("a is {0}, b is {1} ", o, p);
    }
}

 

作者:Work Hard Work Smart

出处:

欢迎任何形式的转载,未经作者同意,请保留此段声明!

 

 
 

转载于:https://www.cnblogs.com/shuai-bySty/p/5110476.html

你可能感兴趣的文章
使用twisted编写异步服务器
查看>>
Python网络编程总结
查看>>
DOM基础知识(Node对象、Element对象)
查看>>
poj2243 && hdu1372 Knight Moves(BFS)
查看>>
14.Vue 定义全局函数
查看>>
linux之"server" directive is not allowed here in
查看>>
LeetCode-43-Multiply Strings
查看>>
android开发学习中的问题:error: device not found解决办法
查看>>
SoapUI、Jmeter、Postman三种接口测试工具的比较
查看>>
网络爬虫(1)
查看>>
C#初学者对Equals方法的几个常见误解
查看>>
CodeForces 103D Time to Raid Cowavans 询问分块
查看>>
自动关闭Messbox
查看>>
apache的开源项目-模板引擎(Velocity)(转)
查看>>
dbus 和 policykit 实例篇(python) ()转
查看>>
大型网站架构系列:消息队列(二) (转)
查看>>
HBase应用笔记:HTable基本概念 (转自淘宝Taobao QA Team)
查看>>
jQuery实现滚动按纽特效
查看>>
pc端图片文件上传
查看>>
基于jquery的表格动态创建,自动绑定,自动获取值
查看>>