从CLR的角度看,关键字out和关键字ref是等效的,这就是说,无论使用哪个关键字,都会生成相同的元数据和IL代码。但是,C#编译器将两个关键字区别对待,在C#中,这两个关键字的区别在于哪个方法负责初始化引用对象。如果方法的参数标记为out,那么调用者不希望在调用方法之前初始化对象,被调用的方法不能读取对象的值,而且被调用的方法必须在返回之前为对象赋值。如果方法的参数标记为ref,那么调用者必须在调用方法之前首先初始化参数的值,被调用的方法可以读取参数或为参数赋值。
namespace 方法参数
{
/// <summary>
/// 参数测试
/// </summary>
class Program
{
static void Main(string[] args)
{
//输出参数
Point p = new Point(10, 12);
int x, y;//输出参数不需要赋初值
p.GetPoint(out x, out y);
Console.WriteLine("p({0},{1})", x, y);
//引用参数
Point2 p1 = new Point2(12, 23);
int x1 = 0, y1 = 0;//引用参数一定要赋初值
p1.GetPoint(ref x1, ref y1);
Console.WriteLine("p1({0},{1})", x1, y1);
// 参数数组
int[] a = { 1, 2, 3, 4, 5 };
Array.F(a);
Array.F(10, 20, 30, 60, 50);//F(new int[] {10, 20, 30, 60, 50})
Array.F();
Console.ReadLine();
}
}
/// <summary>
/// 输出参数可返回多个值
/// </summary>
class Point
{
int X, Y;
public Point(int x, int y)
{
this.X = x;
this.Y = y;
}
public void GetPoint(out int x, out int y)
{
y = this.Y;
x = this.X;
}
}
/// <summary>
/// 引用参数
/// </summary>
class Point2
{
int X, Y;
public Point2(int x, int y)
{
this.X = x;
this.Y = y;
}
public void GetPoint(ref int x, ref int y)
{
y = this.Y;
x = this.X;
}
}
/// <summary>
/// 参数数组
/// </summary>
class Array
{
public static void F(params int[] args)
{
Console.WriteLine("数组长度为:{0}", args.Length);
foreach (int i in args)
{
Console.WriteLine("{0}", i);
}
Console.WriteLine();
}
}
}
namespace 方法参数
{
/// <summary>
/// 参数测试
/// </summary>
class Program
{
static void Main(string[] args)
{
//输出参数
Point p = new Point(10, 12);
int x, y;//输出参数不需要赋初值
p.GetPoint(out x, out y);
Console.WriteLine("p({0},{1})", x, y);
//引用参数
Point2 p1 = new Point2(12, 23);
int x1 = 0, y1 = 0;//引用参数一定要赋初值
p1.GetPoint(ref x1, ref y1);
Console.WriteLine("p1({0},{1})", x1, y1);
// 参数数组
int[] a = { 1, 2, 3, 4, 5 };
Array.F(a);
Array.F(10, 20, 30, 60, 50);//F(new int[] {10, 20, 30, 60, 50})
Array.F();
Console.ReadLine();
}
}
/// <summary>
/// 输出参数可返回多个值
/// </summary>
class Point
{
int X, Y;
public Point(int x, int y)
{
this.X = x;
this.Y = y;
}
public void GetPoint(out int x, out int y)
{
y = this.Y;
x = this.X;
}
}
/// <summary>
/// 引用参数
/// </summary>
class Point2
{
int X, Y;
public Point2(int x, int y)
{
this.X = x;
this.Y = y;
}
public void GetPoint(ref int x, ref int y)
{
y = this.Y;
x = this.X;
}
}
/// <summary>
/// 参数数组
/// </summary>
class Array
{
public static void F(params int[] args)
{
Console.WriteLine("数组长度为:{0}", args.Length);
foreach (int i in args)
{
Console.WriteLine("{0}", i);
}
Console.WriteLine();
}
}
}