• C#学习系列-out与ref的区别


    参考http://www.microsoftvirtualacademy.com/Content/ViewContent.aspx?et=9851&m=9839&ct=31056

    如有错误,欢迎指正

    Out和Ref作为参数传递到方法体中,所传递的都是引用地址,两者在操作上本身没有区别。

    但Out传递到方法体时,参数会清空,这意味着在方法体内使用Out参数前必须赋值。

    而Ref传递到方法体时,其参数也是一起被传递进来,所以作为Ref参数传递,方法体中可以不对其参数赋值。

    下面贴代码

        class Program
        {
            /*ref是有进有出,out是只出不进*/
            static void Main(string[] args)
            {
                /*作为Out参数传递 传递前可以不初始化*/
                string outString = "This is the  outString value";
                Console.WriteLine(outString);
                outMethod(out outString);
                Console.WriteLine(outString);
    
                /*作为Ref参数传递 传递前必须初始化*/
                string refString = "This is the refString value";
                Console.WriteLine(refString);
                refMethod(ref refString);
                Console.WriteLine(refString);
                Console.ReadLine();
    
            }
            static bool outMethod(out string str)
            {
                /*作为Out参数传递 传递到方法体后 参数被清空*/
                //Console.WriteLine(str); Use of unassigned out parameter 'str' 
                /*作为Out参数传递 值必须在方法体内赋值*/
                /*作为Out参数传递 返回前值必须初始化*/
                str = "This is the new outString value";
                return true;
            }
            static bool refMethod(ref string str)
            {
                Console.WriteLine(str);
                /*作为Ref参数传递 返回前值可以不初始化*/
                return true;
            }
        }
    作者:释迦苦僧
    出处:http://www.cnblogs.com/woxpp
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
    生活不易,五行缺金,求打点
  • 相关阅读:
    怎样在过滤器中读取配置信息?
    怎样将直接数据库中Json字段,映射到Mybatis中的Map类型?
    spring/boot 打包,资源/配置/业务文件分离
    使用VS Code推送代码到GitHub
    Clion下jni配置
    curl post请求总是返回417错误
    ubuntu 12.10 apt-get 源
    如何让git小乌龟工具TortoiseGit记住你的账号密码
    FastCgi与Cgi
    Libevent核心原理
  • 原文地址:https://www.cnblogs.com/woxpp/p/3907944.html
Copyright © 2020-2023  润新知