C# ref and out的使用小结
相同点:
1.ref和out都是按地址传递的,使用后都将改变原来参数的数值;
2.方法定义和调用方法都必须显式使用ref或者out关键字;
3.通过ref和ref特性,一定程度上解决了C#中的函数只能有一个返回值的问题。
不同点:
传递到 ref 参数的参数必须初始化,否则程序会报错。
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Threading.Tasks; namespaceConsoleApplication1 { classProgram { staticvoidMain(string[]args) { inta=1; intb=2; Fun(refa,refb); Console.WriteLine("a:{0},b:{1}",a,b);//输出:3和4说明传入Fun方法是a和b的引用 } staticvoidFun(refinta,refintb){ a=3; b=4; } } }
out关键字无法将参数值传递到out参数所在的方法中,out参数的参数值初始化必须在其方法内进行,否则程序会报错。
usingSystem.Text; namespaceConsoleApp1 { classProgram { staticvoidMain(string[]args) { inta=100; intb; Fun(outa,outb); Console.WriteLine("a:{0},b:{1}",a,b); } staticvoidFun(outinta,outintb) { //a=1+2; if(a==100) a=2; b=1; } } }
代码里报错“Useofunassignedoutparameter'a'”
下面的代码是正确的。
usingSystem; namespaceConsoleApp1 { classProgram { staticvoidMain(string[]args) { inta=100; intb; Fun(outa,outb); Console.WriteLine("a:{0},b:{1}",a,b); } staticvoidFun(outinta,outintb) { a=1+2; b=1; } } }
输出结果为:
注意点:
usingSystem; namespaceConsoleApplication1 { classProgram { publicvoidSampleMethod(refinti){} publicvoidSampleMethod(outinti){} } }
上面代码会报错“'Program'cannotdefineanoverloadedmethodthatdiffersonlyonparametermodifiers'out'and'ref' ”
尽管 ref 和 out 在运行时的处理方式不同,但在编译时的处理方式相同。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个方法是完全相同的,因此将不会编译上面的代码。
usingSystem; namespaceConsoleApplication1 { classProgram { publicvoidSampleMethod(inti){} publicvoidSampleMethod(refinti){} } }
上面代码会报错“'Program'cannotdefineanoverloadedmethodthatdiffersonlyonparametermodifiers'out'and'ref' ”
尽管 ref 和 out 在运行时的处理方式不同,但在编译时的处理方式相同。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个方法是完全相同的,因此将不会编译上面的代码。
usingSystem; namespaceConsoleApplication1 { classProgram { publicvoidSampleMethod(inti){} publicvoidSampleMethod(refinti){} } }
但是,如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两个参数,则可以进行重载。
以上就是C#refandout的使用小结的详细内容,更多关于C#refandout的使用的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。