首页 > 其他 > 详细

ref和out

时间:2014-04-10 21:04:22      阅读:507      评论:0      收藏:0      [点我收藏+]

ref(C# 参考)

ref keyword causes an argument to be passed by reference, not by value.‘ data-guid="85491a3de2da7f15020c46c165e91e3d">ref 关键字会导致通过引用传递的参数,而不是值。 通过引用传递的效果是在方法中对参数的任何改变都会反映在调用方的基础参数中。 引用参数的值与基础参数变量的值始终是一样的。

bubuko.com,布布扣 说明

不要将“通过引用传递”概念与“引用类型”概念相混淆。 这两个概念不同。 ref regardless of whether it is a value type or a reference type.‘ data-guid="e66925f794a9fc89203b42886b887d6c">方法参数无论是值类型还是引用类型,都可通过 ref 进行修饰。 通过引用传递值类型时没有值类型装箱。

ref parameter, both the method definition and the calling method must explicitly use the ref keyword, as shown in the following example.‘ data-guid="81b0fd55ff25eb50bd1310a85b580af4">如下面的示例所示,若要使用 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
        }
    }



ref parameter must be initialized before it is passed.‘ data-guid="f9c9ea747c0a9c2b592098f9bdff514c">传递给 ref 参数的参数必须初始化,则通过之前。 out parameters, whose arguments do not have to be explicitly initialized before they are passed.‘ data-guid="151e11c88d5ddb8ad0d5d7609ec5fcf8">这与 out 参数不同,参数不需要显式初始化,在通过之前。 out.‘ data-guid="947cee202b051342b8452bc7cb600270">有关更多信息,请参见 out

选件类的成员不能具有由 ref 和 out仅不同的签名。 ref parameter and the other has an out parameter.‘ data-guid="2c2f32f716ce0ce8234acd0fa8650b2b">编译器错误,如果类型之间的两个成员的唯一区别是其中一个具有 ref 参数,另一个 out 参数。 下面的代码,例如,无法生成。

 

再来看一下out:out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。若要使用 out 参数,方法定义和调用方法都必须显式使用 out 关键字。

示例:

bubuko.com,布布扣
bubuko.com,布布扣
        static void Method(out int i)
        {
            i = 44;
        }

        static void Main(string[] args)
        {
            int val;
            Method(out val);
            Console.WriteLine(val);              // val is now 44
            Console.ReadLine();
        }
bubuko.com,布布扣
bubuko.com,布布扣

尽管作为 out 参数传递的变量不必在传递之前进行初始化,但需要调用方法以便在方法返回之前赋值。

ref  out 关键字在运行时的处理方式不同,但在编译时的处理方式相同。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个方法是完全相同的,因此将不会编译以下代码:

http://images.cnitblog.com/blog/401119/201401/02231604-5e34e6d7dcb248f09c94289df4e122c1.png

但是,如果一个方法采用 ref  out 参数,而另一个方法不采用这两类参数,则可以进行重载,如下所示:

bubuko.com,布布扣
        public void SampleMethod( int i) { }

        public void SampleMethod(ref int i) { }

部分资料参考:http://www.cnblogs.com/aehyok/p/3499822.html
bubuko.com,布布扣

ref和out,布布扣,bubuko.com

ref和out

原文:http://www.cnblogs.com/Revel/p/3656416.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!