看下面这段程序:
static void Main(string[] args)
{
int i;
int j;
Add (ref i,ref j);
Console.WriteLine(i);
Console.WriteLine(j);
}
static void Add(ref int i, ref int j)
{
i = 1;
j = 2;
}
编译结果:
Use of unassigned local variable 'i'
Use of unassigned local variable 'j'
如果改成:
static void Main(string[] args)
{
int i;
int j;
Add(out i, out j);
Console.WriteLine(i);
Console.WriteLine(j);
}
static void Add(out int i, out int j)
{
i = 1;
j = 2;
}
运行结果:
1
2
知道out和ref的区别了吧?
按引用传递的参数out和ref, ref在使用前需要初始化变量的值。
