C#引用参数和输出参数的区别

C#引用参数和输出参数的区别

(2009-12-27 17:51:59)

CLR的角度看,关键字out和关键字ref是等效的,这就是说,无论使用哪个关键字,都会生成相同的元数据和IL代码。但是,C#编译器将两个关键字 区别对待,在C#中,这两个关键字的区别在于哪个方法负责初始化引用对象。如果方法的参数标记为out,那么调用者不希望在调用方法之前初始化对象,被调 用的方法不能读取对象的值,而且被调用的方法必须在返回之前为对象赋值。如果方法的参数标记为ref,那么调用者必须在调用方法之前首先初始化参数的值, 被调用的方法可以读取参数或为参数赋值。

namespace 方法参数
{
    /// <summary>
    /// 参数测试
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            //输出参数
            Point p = new Point(10, 12);
            int x, y;//输出参数不需要赋初值//与引用类型相似,输出参数也不开辟新的内存区域, 

但在调用方法前无需对变量进行初始化。
            p.GetPoint(out x, out y);
            Console.WriteLine("p({0},{1})", x, y);
            //引用参数
            Point2 p1 = new Point2(12, 23);
            int x1 = 0, y1 = 0;//引用参数一定要赋初值
            p1.GetPoint(ref x1, ref y1);
            Console.WriteLine("p1({0},{1})", x1, y1);
            // 参数数组
            int[] a = { 1, 2, 3, 4, 5 };
            Array.F(a);
            Array.F(10, 20, 30, 60, 50);//F(new int[] {10, 20, 30, 60, 50})
            Array.F();
            Console.ReadLine();
        }
    }
    /// <summary>
    /// 输出参数可返回多个值
    /// </summary>
    class Point
    {
        int X, Y;
        public Point(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
        public void GetPoint(out int x, out int y)//输出参数用于传递方法返回的数据。out修饰符后应跟与形参类型相同的类型申明。在方法返回后,传递的变量被认为经过了初始化。
        {
            y = this.Y;
            x = this.X;
        }
    }
    /// <summary>
    /// 引用参数
    /// </summary>
    class Point2
    {
        int X, Y;
        public Point2(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
        public void GetPoint(ref int x, ref int y)
        {
            y = this.Y;
            x = this.X;
        }
    }
    /// <summary>
    /// 参数数组
    /// </summary>
    class Array
    {
        public static void F(params int[] args)
        {
            Console.WriteLine("数组长度为:{0}", args.Length);
            foreach (int i in args)
            {
                Console.WriteLine("{0}", i);
            }
            Console.WriteLine();
        }
    }
}

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/niehoude/archive/2009/08/03/4403100.aspx

原文地址:https://www.cnblogs.com/tabcdt/p/2916722.html