欢迎光临散文网 会员登陆 & 注册

方法/函数6(ref参数)

2023-01-26 22:50 作者:此城过客  | 我要投稿

static void Jiangjin(double s)

{ s += 500 ; }

static void Main(string[] args)

{

       double salary = 5000;

       Jiangjin(salary);

       Console.WriteLine(salary);

}

上面这个语句,按以往的规则,属于是错误的。但是用ref参数,可以改进。

static void Jiangjin(ref double s)

{ s += 500 ; }

static void Main(string[] args)

{

       double salary = 5000;

       Jiangjin(ref salary);

       Console.WriteLine(salary);

}

自从加了这个ref之后,就可以运行了。因此ref参数,就相当于是连通器,方法里的值改了,

主函数里是可以通过这个接收到的。

第二个例子,交换值:

static void Test(ref int a,ref int b)

{ int temp = a ; a = b ; b = temp ; }

static void Main(string[] args)

{

        int s = 20;

        int w = 10;

        Test(ref s,ref w);

        Console.WriteLine(s);

        Console.WriteLine(w);

}


方法/函数6(ref参数)的评论 (共 条)

分享到微博请遵守国家法律