方法/函數(shù)6(ref參數(shù))
static void Jiangjin(double s)
{ s += 500 ; }
static void Main(string[] args)
{
? ? ? ?double salary = 5000;
? ? ? ?Jiangjin(salary);
? ? ? ?Console.WriteLine(salary);
}
上面這個(gè)語句,按以往的規(guī)則,屬于是錯(cuò)誤的。但是用ref參數(shù),可以改進(jìn)。
static void?Jiangjin(ref?double?s)
{?s += 500 ;?}
static void?Main(string[] args)
{
? ? ? ?double?salary = 5000;
? ? ? ?Jiangjin(ref salary);
? ? ? ?Console.WriteLine(salary);
}
自從加了這個(gè)ref之后,就可以運(yùn)行了。因此ref參數(shù),就相當(dāng)于是連通器,方法里的值改了,
主函數(shù)里是可以通過這個(gè)接收到的。
第二個(gè)例子,交換值:
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);
}
標(biāo)簽: