zoukankan      html  css  js  c++  java
  • ref与out的区别

    ref与out都是可以通过给方法传递值类型的参数,直接操作同一个变量的关键字。

    区别:当你在使用ref传递参数的时候,ref修饰的参数必须要有值,但是out可以使用一个未赋值的变量作为参数传递。

    为什么Out不需要赋值呢?

    不管有没有对静态变量outInt赋值,只要出使用out修饰符,就必须对out修饰的参数outIntPar赋值。
    所以out应该是在方法内部做了分配地址的操作,然后把地址赋给外部的变量。但是ref的话是直接传递外部地址进方法。

     static void Main(string[] args)
            {
                int number = 1;
                int number2 = 1;
                int number3 = 1;//或者直接定义 int number3;
                Method(number);
                Method2(ref number2);
                Method3(out number3);
                Console.WriteLine(number);//1
                Console.WriteLine(number2);//67
                Console.WriteLine(number3);//66
                Console.Read();
    }
      public static int Method(int myRefInt)
            {
                myRefInt += 66;
                var a = myRefInt;
                return a;
            }
            static void Method2(ref int myRefInt)
            {
                myRefInt += 66;
                var a = myRefInt.ToString();
            }
            static void Method3(out int myRefInt)
            {
                myRefInt = 66;//这里不能像上面一样用 +=,因为会提示使用了未赋值的out参数"myRefInt"
                var a = myRefInt.ToString();
            }
  • 相关阅读:
    《TD项目开发小结》
    感悟
    毕业两年了
    ip+port无法访问nginx问题
    问题解决之道
    调休9天的那些日子
    关于类加载器(ClassLoader)
    ios核心蓝牙之心率监控(swift)
    git(git-flow)的高效管理使用
    WKWebview加载本地图片时出现路径问题
  • 原文地址:https://www.cnblogs.com/macT/p/10881980.html
Copyright © 2011-2022 走看看