c#中ref 与 out关键字的几点总结

实践的时候对ref与out关键字的几点总结,没太多技术含量,但也是本人劳动成果,入门同志可以参考参考,不要见笑噢。
1、ref与out一般指引用传递,比如方法的参数传递,其效果是,当控制权传递回调用方法时,在方法中对参数的任何更改都将反映在该变量中。
2、若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。
3、不能以out ref 的区别来重载方法;。
4、关于out 关键字,与ref关键字的唯一区别是在调用函数是参数不需要初使化。
5、可以用于返回多值函数。
6、不能在匿名方法外部使用的ref和out参数。
7、对于结构型,初使化快或删除等操作很快,但复制慢,在作为参数传入方法时可以作为ref参数传递。以避免性能损失.
using System;
class RefExample
{
    static void Method(ref int i)
    {
        i = 44;
    }
     //static void Method(out int i)
    // {
    //  i= 55;
   // }
    static void Method(int i)
    {
     i = 33;
    }
   
    static void Method2(out int n,out string ss)
    {
     n = 55;
     ss = "abcd";
    }
    static void Main()
    {
        int val = 0;
        int n;
        string ss;
        Method(ref val);
        Method2(out n,out ss);
        Console.WriteLine("val={0:N},\nn={1:D},\nss={2}",val,n,ss);
        // val is now 44
    }
}

.net技术交流和畅想欢迎加Q群44872096

猜你喜欢

转载自blog.csdn.net/lixuezhi/article/details/9566555
今日推荐