ref是传递参数的地址,跟C++行数的引用一样。使用ref前必须对参数进行初始化。Ref表示的参数在函数体里可以修改也可以不不被修改。
out修饰的传递参数可以不用赋值,函数会清空该参数变量,不管变量传递前是否已经赋值。退出参数都需要赋值。
using System;
class Class1
{
public static void OutTest(out int x , out int y)
{
x = 0 ; y = 1; //如果不赋值将提示编译出错
Console.WriteLine("x={0},y={1}",x,y);
}
public static void RefTest(ref int x , ref int y)
{
x=111; y=222;
Console.WriteLine("x={0},y={1}",x,y);
}
/// <summary>
/// 应用程序的主入口点。
/// </summary>
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
int x = 12,y = 11;
OutTest(out x,out y);
Console.WriteLine( "x = {0}, y={1}",x,y);
int a = 2, b= 1;//如果不赋值将提示编译出错
RefTest(ref a ,ref b);
Console.WriteLine( "a = {0}, b={1}",a,b);
Console.ReadLine();
}
}