读书人

C# Keywords Series 七 refamp;out

发布时间: 2013-01-26 13:47:01 作者: rapoo

C# Keywords Series 7 ref&out

本文主要讲述 ref 和 out 两个关键字使用和区别。

ref

ref 关键字通过引用(可以理解为传递地址)传递参数,参数可以是任何类型(值类型或者引用类型),所以方法中该变参数的值会同步到基础参数上,看代码。

    class Program    {        static void RefMethod(ref int i)        {            i = i + 1;        }        static void Main(string[] args)        {            int val = 1;            RefMethod(ref val);            Console.WriteLine(val);            // Output :2        }    }


传递给 ref 参数前,基础参数必须初始化。相比较 out 修饰的参数认为参数没有初始化,方法中必须赋值。这是两个关键字重要区别。两个修饰符一起修饰相同方法的仅 ref 和out 签名不同不能够重载,会报编译错误。

   // Compiler error :The out parameter 'i' must be assigned to before control leaves the current method        public void TestMethod(ref int i) { }        public void TestMethod(out int i) { }


但是,当只有一个方法具有 ref 或 out 时 ,是可以重载的。

  public void TestMethod(ref int i) { }  public void TestMethod( int i) { }


out

out 关键字也是通过引用传递参数,可以看例子。

    class Program    {        static void OutMethod(out int i)        {            i =  10 ;        }        static void Main(string[] args)        {            int val;            OutMethod(out val);            Console.WriteLine(val);            // Output :10        }    }


同样方法中改变参数的值,基础参数也会同步的改变。这里还要说一下,当希望返回多个值时,out 关键字就起到作用了,而且可以有选择的返回值。

 class Program    {        static void OutMethod(out int i,out string s1,out string s2)        {            i =  10 ;            s1 = "Updated by OutMethod";            s2 = null;        }        static void Main(string[] args)        {            int val;            string s1, s2;            OutMethod(out val,out s1,out s2);            Console.WriteLine("val:{0}  s1:{1}  s2:{2}",val,s1,s2);            // Output :val:10  s1:Updated by OutMethod  s2:        }    }


简单介绍为止。楼主最近很郁闷,草草地写了这一篇。

读书人网 >C#

热点推荐