ref、out参数

时间:2023-03-09 06:30:09
ref、out参数

ref和out都是表示按引用传递。与指针类似,直接指向同一内存。

按值传递参数的方法永远不可能改变方法外的变量,需要改变方法外的变量就必须按引用传递参数。

传递参数的方法,在C语言里,用指针。在C#里,可以用指针,但是更通常也更安全的做法就是用ref。

namespace ConsoleApplication1
{
class Program
{
int Add(int x,int y)
{
x = x + y;
return x;
}
int Add(ref int x,int y)
{
x = x + y;
return x;
}
int Add(int x,int y,out int z)
{
z = x + y;
return z;
}
int Add(params int[] x)//可变长参数数组
{
int result = ;
for (int i = ; i < x.Length; i++)
{
result += x[i];
}
return result;
}
static void Main(string[] args)
{
Program p = new Program();
int x = , y = ;
int z;
Console.WriteLine("值参数" + p.Add(x, y));
Console.WriteLine(x);//30,方法内的x与外部x不是同一内存
Console.WriteLine("ref参数" + p.Add(ref x, y));
Console.WriteLine(x);//70,引用传参,指向同一内存
Console.WriteLine("out参数" + p.Add(x, y, out z));
Console.WriteLine("params参数" + p.Add(, , , ));
}
}
}

关于params,参考 https://blog.csdn.net/wcc27857285/article/details/80991824

ref、out的更多内容,参考 https://www.cnblogs.com/vd630/p/4601919.html