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

    若要使用 ref 参数,方法定义和调用方法均必须显式使用 ref 关键字,如下面的示例所示。

    class RefExample
    {
        static void Method(ref int i)
        {
            // Rest the mouse pointer over i to verify that it is an int.
            // The following statement would cause a compiler error if i
            // were boxed as an object.
            i = i + 44;
        }
    
        static void Main()
        {
            int val = 1;
            Method(ref val);
            Console.WriteLine(val);
    
            // Output: 45
        }
    }

     

    out的使用

     class Program
        {
            static void ResoluteName(string fullname, out String firstname, out string lastname)
            {
                string[] strArray = fullname.Split(new char[] { ' ' });
                firstname = strArray[0];
                lastname = strArray[1];
            }
            static void Main(string[] args)
            {
                Console.WriteLine("请输入你的姓名,姓和名之间有空格分隔:");
                string MyName = Console.ReadLine();
                string MyFirstName, MylastName;
                ResoluteName(MyName, out MyFirstName, out MylastName);
                Console.WriteLine("My first name:{0}", MyFirstName);
                Console.WriteLine("My last name:{0}", MylastName);
                Console.Read();
            }
        }

    传递到 ref 形参的实参必须先经过初始化,然后才能传递。这与 out 形参不同,在传递之前,不需要显式初始化该形参的实参。

    转载于  C#参考

  • 相关阅读:
    week8
    2020中国大学生程序设计竞赛(CCPC)-网络选拔赛 题解
    卷积形式dp的多项式求逆做法
    多项式乘法逆(review)
    LaTex学习
    BZOJ 2653 middle
    BZOJ3207 花神的嘲讽计划Ⅰ
    BZOJ1901 Zju2112 Dynamic Rankings
    POJ2104 K-th Number
    平衡树总结专题
  • 原文地址:https://www.cnblogs.com/liujiayun/p/5381462.html
Copyright © 2011-2022 走看看