ref关键字
ref是引用的方式传递参数,参数必须初始化 。也就意味传入方法中的不再是形参,而是引用该实参 。ref关键字在定义 和 使用时需要在前面添加 ref关键字表示引用,对比代码如下:
ref引用传参
cs
//ref:引用的方式传递参数
public static int findMax(ref int num1, ref int num2)
//public static int findMax(int num1, int num2)
{
num1 *= 2;
num2 *= 2;
return num1 + num2;
}
private static void Main(string[] args)
{
//参数必须初始化不然会报错
int num1 = 1;
int num2 = 2;
int num3 = 0;
num3 = findMax(ref num1, ref num2);
//num3 = findMax(num1, num2);
Console.WriteLine($"num1 = {num1}, num2 = {num2}, num3 = {num3}");
//num1 = 2, num2 = 4, num3 = 6
Console.ReadKey();
}
值传参
cs
//ref:引用的方式传递参数
//public static int findMax(ref int num1, ref int num2)
public static int findMax(int num1, int num2)
{
num1 *= 2;
num2 *= 2;
return num1 + num2;
}
private static void Main(string[] args)
{
//参数必须初始化不然会报错
int num1 = 1;
int num2 = 2;
int num3 = 0;
//num3 = findMax(num1, num2);
num3 = findMax(num1, num2);
Console.WriteLine($"num1 = {num1}, num2 = {num2}, num3 = {num3}");
//num1 = 1, num2 = 2, num3 = 6
Console.ReadKey();
}
out关键字
out关键字与ref关键字一样也是引用传递,在使用out修饰的参数,在定义的时候,可以初始化,也可以不初始化,但是,在方法内部必须赋值。
out输出传参
cs
public static int result(int num1, int num2, out int num3)
//public static int result(int num1, int num2, int num3)
{
num3 = (num1 + num2) / 2;
return num3;
}
private static void Main(string[] args)
{
int num1 = 2;
int num2 = 4;
int num3 = 0;
int avg = 0;
avg = result(num1, num2, out num3);
//avg = result(num1, num2, num3);
Console.WriteLine($"avg = {avg}, num3 = {num3}"); //avg = 3, num3 = 3
Console.ReadKey();
}
值传递
cs
//public static int result(int num1, int num2, out int num3)
public static int result(int num1, int num2, int num3)
{
num3 = (num1 + num2) / 2;
return num3;
}
private static void Main(string[] args)
{
int num1 = 2;
int num2 = 4;
int num3 = 0;
int avg = 0;
//avg = result(num1, num2, out num3);
avg = result(num1, num2, num3);
Console.WriteLine($"avg = {avg}, num3 = {num3}"); //avg = 3, num3 = 0
Console.ReadKey();
}