ref 和out的用法以及区别

在项目其实很少用ref和out,但是我们常用的工具resharep在帮我们重构的时候难免会给我们重构成带有ref或者是out的方法. 本人也是用的少所以难免忘记,留下简略笔记,以供后来自我参考:

为何要用ref或者是out:  当我们需要向一个方法传递一个参数时但是又要得到这个参数的变化值的时候

ref:

public void Ref(ref string s){
	s="ref s";
}
void Main()
{
	string s="agas s";//必须要声明并初始化
 	Ref(ref s);         //传递带有ref的参数
	Console.WriteLine(s); //ref s
}

out:

public void Out(out string s){
	s="out s";
}
void Main()
{
	string s; //只需要声明,没有必要显示初始化
	Out(out s); //传递带有out的参数
	Console.WriteLine(s); //out s
}

注明:

1,当传递参数我们实际传递都是一个引用

2,不管是ref还是out其实生成的IL其实都是一样的

3,A(ref  int s),A(out int s)此种类型不能重载(与非ref或者是out方法可以重载)

原文地址:https://www.cnblogs.com/objectboy/p/4575249.html