您的位置:首页 > 编程语言 > C#

C#中out和ref之间的区别

2018-02-27 21:38 344 查看
ref参数是引用,out参数为输出参数。

ref的使用:使用ref进行参数的传递时,该参数在创建时,必须设置其初始值,且ref侧重于修改;

out的使用: 采用out参数传递时,该参数在创建时,可以不设置初始值,但是在方法中必须初始化,out侧重于输出;

public class Base
{
public void outMethod(out string x)
{
x = "this is outMethod";
}
public void refMethod(ref string x)
{
x = "this is refMethod";
}
}


  

static void Main(string[] args)
{

Base ba = new Base();

string i;//可以不初始化。因为out
ba.outMethod(out i);
Console.WriteLine(i);

string j = "0";//必须初始化,因为ref
ba.refMethod(ref j);
Console.WriteLine(j);
Console.ReadLine();
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: