ref和out的相同和不同的讨论

ref和out均是传址调用,不同点在于:

ref在传入前必须赋值

out在传入前不必赋值,但是在返回的时候因为之前没有保证被赋值,所以返回前必须赋值

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class TestApp
    {
        static void outTest(out int x, out int y)
        {//离开这个函数前,必须对x和y赋值,否则会报错。 
            //y = x; 
            //上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行 
            x = 1;
            y = 2;
        }
        static void refTest(ref int x, ref int y)
        {
            x = 1;
            y = x;
        }
        public static void Main()
        {
            //out test
            int a, b;
            //out使用前,变量可以不赋值
            outTest(out a, out b);
            Console.WriteLine("a={0};b={1}", a, b);
            int c = 11, d = 22;
            outTest(out c, out d);
            Console.WriteLine("c={0};d={1}", c, d);
            //ref test
            int m, n;
            //refTest(ref m, ref n); 
            //上面这行会出错,ref使用前,变量必须赋值
            int o = 11, p = 22;
            refTest(ref o, ref p);
            Console.WriteLine("o={0};p={1}", o, p);
        }
    }
    //ref在传入前必须赋值
    //out在传入前不必赋值,但是在返回的时候因为之前没有保证被赋值,所以返回前必须赋值
}
原文地址:https://www.cnblogs.com/lihaozy/p/1866051.html