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#参考

  • 相关阅读:
    2-Fourteenth Scrum Meeting-20151214
    2-Thirteenth Scrum Meeting-10151213
    2-Twelfth Scrum Meeting20151212
    2-Eleventh Scrum Meeting20151211
    L465 Climate Change May Take Away Your Ability to Flush the Toilet
    L458 Interview
    L457 早上锻炼减肥
    L456 学英语 看美剧
    L455 人之初,性本衰
    L454 正确喝水
  • 原文地址:https://www.cnblogs.com/liujiayun/p/5381462.html
Copyright © 2011-2022 走看看