c sharp中ref的作用是什么

如题所述

作用:

1 . ref:MSDN的定义为The ref keyword indicates a value that is passed by reference。就是通过引用来传递参数。

2 . 方法参数上的 ref 方法参数关键字使方法引用传递到方法的同一个变量,当控制传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。若要使用 ref 参数,必须将参数作为 ref 参数显式传递到方法,ref 参数的值被传递到 ref 参数,传递到 ref 参数的参数必须最先初始化。

运行代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ref_out

{

    class Program

    {

        static void Main(string[] args)

        {

            int i = 8;

            Console.WriteLine(i);

            DoIncrease(i);

            Console.WriteLine(i);

        }

 

        static void DoIncrease(int a)

        {

            a++;

        }

    }

}

运行结果如下:

扩展资料:

(1)不使用ref的时候,函数收到的值是1,然后在Method(int myRefInt)方法中,局部变量myRefInt做了累加之后,在方法执行完成之后就已经销毁了,number的值还是1。

(2)使用ref的时候,函数Method(ref int myRefInt)值收到的是number的地址,函数中执行的myRefInt+=66,此时相当于number+=66,直接修改了number地址的值。



温馨提示:答案为网友推荐,仅供参考
相似回答