C#out关键字
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/227
out关键字和ref关键字很像,什么是ref关键字看→这里
相同点:
ref和out都是按地址传递,使用后都将改变原来参数的数值。
区别:
out参数在传入前不需要初始化
ref参数在传入前需要初始化
优势:
out更灵活一些
详细:
使用out,参数是不可以等于自己的,直接不合法,
使用ref,参数是可以等于自己的,会警告但能用。
ref使用例:
static void Main(string[] args)
{
int a = 6;
int b = 66;
Fun(ref a, ref b);
Console.WriteLine("a:{0},b:{1}", a, b);
Console.Read();
}
static void Fun(ref int a, ref int b)
{
a = a + b;
b = 6;
}
输出:
a:72,b:6
out使用例:
static void Main(string[] args)
{
int a = 100;
int b;
Fun(out a, out b);
Console.WriteLine("a:{0},b:{1}", a, b);
Console.Read();
}
static void Fun(out int a, out int b)
{
a = 1 + 2;
b = 1;
}
输出:
a:3,b:1
out关键字无法将参数的值传递到out参数所在的方法中,只能传递对参数的引用,
所以out参数的参数值初始化必须在其方法内进行,否则程序会报错。
ref和out最主要的区别是:
ref将参数的参数值和引用都传入方法中,所以ref的参数的初始化必须在方法外部进行,也就是ref的参数必须有初始化值,否则程序会报错;
out不会将参数的参数值传入方法中,只会将参数的引用传入方法中,所以参数的初始化工作必须在其对用方法中进行,否则程序会报错。
为什么会出现ref和out?
ref和out并不是为了简化代码而出现的,本来一个ref能解决的问题,为什么要出现一个out?
out关键字就这个单词本身的意思一样,out是作为输出的,
你不应当去input一个值给out。
有一个out最典型的用法:
int arr[]={1,2,3,4,5};
int max,min;
float average;
你首先不应该对max、min、average赋值,因为这些变量是你想求出的结果。
那么out关键字就派上用场了,
UseOut(arr, out max,out min,out average);
是的,你不需要去纠结这个方法内部怎么实现的,
你只需要填入你的数组,然后填入你的承载结果的容器max、min、average,就已经完成了。
参考文档:
This article was last edited at 2020-04-03 07:42:07