ref
ref:MSDN的定义为:“The ref keyword indicates a value that is passed by reference.”就是通过引用来传递参数。ref也是Reference的缩写。
不使用ref
using System;
namespace Test_Code
{
class A
{
public void Method( int a)
{
a += 1;
}
public static void Main()
{
int c = 10;
A B = new A();
B.Method(c);
Console.WriteLine(c);
}
}
}
//输出10
使用ref关键字
using System;
namespace Test_Code
{
class A
{
public void Method(ref int a)
{
a += 1;
}
public static void Main()
{
int c = 10;
A B = new A();
B.Method(ref c);
Console.WriteLine(c);
}
}
}
//输出11
总结
不使用ref关键字的时候,函数收到的值是10,然后在Method(int a)方法中,局部变量a做了累加之后,在方法执行完成之后就已经销毁了。c的值还是10。
使用ref关键字的时候,函数Method(ref int a)值收到的是c的地址,函数中执行的a+=66;此时相当于c+=66;直接修改了c地址的值。
所以ref是通过给方法传递值类型的参数,直接操作同一个变量的关键字。
out
out的定义:As a parameter modifier, which lets you pass an argument to a method by reference rather than by value. “out”作为一个参数修饰符,允许您通过引用而不是通过值将参数传递给方法。
In generic type parameter declarations for interfaces and delegates, which specifies that a type parameter is covariant./在接口和委托的泛型类型参数声明中,它指定类型参数是协变的。今天的语境下,我们只讨论第一种作为引用传递参数的定义。
int number;
Method(number);
void Method(int a)
{
a = 66;
}
Console.WriteLine(number);
//输出:0
int number;
Method(out number);
void Method(out int a)
{
a = 66;
}
Console.WriteLine(number);
//输出:66
总结
从上述out用法的表现来看,out和ref其实都可以允许通过引用来传递参数。
ref和out的区别:
当你在使用ref传递参数的时候,ref修饰的参数必须要有值,但是out可以使用一个未赋值的变量作为参数传递。
using System;
namespace Test_Code
{
class RefAndOut
{
public static void OutDouble(out int out_int)
{
out_int = 2;
Console.WriteLine(out_int);
}
public static void RefDouble(ref int ref_int)
{
ref_int *= 2;
Console.WriteLine(ref_int);
Console.ReadKey();
}
public static void NormalDouble(int IntPar)
{
IntPar = 1;
IntPar *= 2;
Console.WriteLine( IntPar);
Console.ReadKey();
}
static void Main(string[] args)
{
int out_int;
int ref_int;
int normalInt;
OutDouble(out out_int);
RefDouble(ref ref_int);//错误:使用了未赋值的变量refInt
NormalDouble(normalInt);//错误:使用了未赋值的变量normalInt
}
}
}
这段代码在两处地方有错误:即在使用ref,和不使用修饰符的时候,必须要传递一个有值的参数。所以你看,ref和out几乎就只有一个区别,那就是out可以使用未赋值的变量。
结论:
关键字“ref“和”out”之间的唯一区别就是关键字”out“不要求调用代码初始化要传递的参数值。那么关键字‘ref”什么时候用呢?当您需要确保调用方法已经初始化参数值的时候,您就应该使用关键字“ref”。在上面例子中,能够使用“out“是因为被调用的方法并不依赖于被传递的变量的值。