首页 > 其他 > 详细

关键字ref、out

时间:2019-08-30 19:20:31      阅读:75      评论:0      收藏:0      [点我收藏+]

通常,变量作为参数进行传递时,不论在方法内进行了什么操作,其原始初始化的值都不会被影响;

例如:

技术分享图片
  public void TestFun1()
        {
            int arg = 10;
            TestFun2(arg);
            Console.WriteLine(arg);
            Console.ReadKey();

        }
        public void TestFun2(int x)
        {
            x++;
        }
View Code

通过执行

test1 t = new test1();
t.TestFun1();

其结果输出:10

那么问题来了,如果想要操作有影响要怎么做呢?

简单的操作:添加ref关键字

技术分享图片
 public void TestFun1()
        {
            int arg = 10;
            TestFun2(ref arg);
            Console.WriteLine(arg);
            Console.ReadKey();

        }
        public void TestFun2(ref int x)
        {
            x++;
        }
View Code

执行结果:

技术分享图片

即:形参附加ref前缀,作用于参数的所有操作都会作用于原始实参(参数和实参引用同一个对象);

 

 

out关键字:

  为形参附加out前缀,使参数成为实参的别名。向一个方法传递out参数之后,必须在方法内部对其进行赋值,因此调用方法时不需要对实参进行初始化。(注:如果使用了out关键字,但方法内没有对参数进行赋值,编译器无法进行编译)如果在调用方法前已经对实参初始化,调用方法后参数的值会发生改变,变为方法内赋的值;

技术分享图片
        public void TestFun_out1()
        {
            int arg1;
            int arg2 = 10;
            TestFun_out2(out arg1, out arg2);
            Console.WriteLine("arg1:{0}\narg2:{1}", arg1, arg2);
            Console.ReadKey();
        }
        public void TestFun_out2(out int x , out int y)
        {
            x = 20;
            y = 30;
        }    
View Code

执行结果:

技术分享图片

 

关键字ref、out

原文:https://www.cnblogs.com/Duancf/p/11436526.html

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