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

 

posted @ 2016-04-12 09:46  巴黎的雨季  阅读(161)  评论(0编辑  收藏  举报