ref关键字用于将方法内的变量改变后带出方法外。具体我们通过例子来说明:
例子中,将变量a和b的值交换了。如果没有加ref参数,由于没有Exchange()方法没有返回值,调用后,a和b是不会交换的,但是加了ref后,变量便会在Exchange()中改变后并带出。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace @ref
{
class Program
{
static void Main(string[] args)
{
int a = 0;
int b = 1;
Program p = new Program();
p.Exchange(ref a,ref b);
Console.Write(string.Format("a={0} b={1}",a,b));
Console.ReadKey();//输出为a=1 b=0;
}
//此方法没有返回值,普通情况下变量a、b在此方法中做的改变影响范围仅限于此方法之中;
//因为加了ref,所以变量a、b会将改变带给调用方;
private void Exchange(ref int a,ref int b)
{
int tmp = a;
a = b;
b = tmp;
}
}
}