C#学习系列-out与ref的区别

时间:2023-03-09 18:31:43
C#学习系列-out与ref的区别

参考http://www.microsoftvirtualacademy.com/Content/ViewContent.aspx?et=9851&m=9839&ct=31056

如有错误,欢迎指正

Out和Ref作为参数传递到方法体中,所传递的都是引用地址,两者在操作上本身没有区别。

但Out传递到方法体时,参数会清空,这意味着在方法体内使用Out参数前必须赋值。

而Ref传递到方法体时,其参数也是一起被传递进来,所以作为Ref参数传递,方法体中可以不对其参数赋值。

下面贴代码

    class Program
{
/*ref是有进有出,out是只出不进*/
static void Main(string[] args)
{
/*作为Out参数传递 传递前可以不初始化*/
string outString = "This is the outString value";
Console.WriteLine(outString);
outMethod(out outString);
Console.WriteLine(outString); /*作为Ref参数传递 传递前必须初始化*/
string refString = "This is the refString value";
Console.WriteLine(refString);
refMethod(ref refString);
Console.WriteLine(refString);
Console.ReadLine(); }
static bool outMethod(out string str)
{
/*作为Out参数传递 传递到方法体后 参数被清空*/
//Console.WriteLine(str); Use of unassigned out parameter 'str'
/*作为Out参数传递 值必须在方法体内赋值*/
/*作为Out参数传递 返回前值必须初始化*/
str = "This is the new outString value";
return true;
}
static bool refMethod(ref string str)
{
Console.WriteLine(str);
/*作为Ref参数传递 返回前值可以不初始化*/
return true;
}
}