引用型参数

来源:互联网 发布:淘宝达人直播怎么开通 编辑:程序博客网 时间:2024/06/07 11:08

用ref修饰符声明的参数为引用型参数,不开辟新内存区。当利用引用型参数向方法传递形参时,编译程序将把实际值在内存中的地址传递给方法。

如果在方法中,对引用型参数进行修改,就会影响相应实参的值。

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{    class SwapClass    {        public static void Swap(ref int x,ref int y)        {            x += y;            y = x - y;            x = x - y;        }    }    class Program    {        static void Main(string[] args)        {            int a = 13, b = 19;//a,b初始化            Console.WriteLine("运行结果为:");            Console.WriteLine("a={0},b={1}",a,b);            SwapClass.Swap(ref a,ref b);//引用参数a,b已经初始化,且前面加关键字ref            Console.WriteLine("a={0},b={1}",a,b);            Console.ReadLine();        }    }}


在方法中,引用型参数通常已经初始化。在该例中,方法利用引用参数达到了两个变量值实现交换的目的。

0 0
原创粉丝点击