日期:2014-05-17  浏览次数:20748 次

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


ref是传递参数的地址,out是返回值,两者有一定的相同之处,不过也有不同点。

  使用ref前必须对变量赋值,out不用。

  out的函数会清空变量,即使变量已经赋值也不行,退出函数时所有out引用的变量都要赋值,ref引用的可以修改,也可以不修改。


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


----cite a simple example
using System;
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);
 }
}

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();
        }
    }
}