class Program
{
static void Main(string[] args)
{
//out test
int a, b;
//out使用前,变量可以不赋值
outtest(out a, out b);
Console.WriteLine("a={0};b={1}", a, b);
int c = 11, d = 22;
outtest(out c, out d);
Console.WriteLine("c={0};d={1}", c, d);
//ref test
int m, n;
//reftest(ref m, ref n);
//上面这行会出错,ref使用前,变量必须赋值
int o = 11, p = 22;
reftest(ref o, ref p);
Console.WriteLine("o={0};p={1}", o, p);
}
static void outtest(out int x, out int y)
{//离开这个函数前,必须对x和y赋值,否则会报错。
//y = x;
//上面这行会报错,因为使用了out后,x和y都清空了,需要重新赋值,即使调用函数前赋过值也不行
x = 1;
y = 2;
}
static void reftest(ref int x, ref int y)
{
x = 1;
y = x;
}
1、ref传进去的参数必须在调用前初始化,out不必,即:
int i;
SomeMethod( ref i );//语法错误
SomeMethod( out i );//通过
2、ref传进去的参数在函数内部可以直接使用,而out不可:
public void SomeMethod(ref int i)
{
int j=i;//通过
//...
}
public void SomeMethod(out int i)
{
int j=i;//语法错误
}
3、ref传进去的参数在函数内部可以不被修改,但out必须在离开函数体前进行赋值。