C# 中的 ref 参数和 out 参数有什么区别?
csharpprogrammingserver side programming更新于 2025/10/15 9:52:17
Ref 参数
引用参数是对变量内存位置的引用。通过引用传递参数时,与值参数不同,不会为这些参数创建新的存储位置。
您可以使用 ref 关键字声明引用参数。以下是示例−
示例
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void swap(ref int x, ref int y) {
int temp;
temp = x; /* 保存 x 的值 */
x = y; /* 将 y 赋值给 x */
y = temp; /* 将 temp 赋值给 y */
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
/* 局部变量定义 */
int a = 100;
int b = 200;
Console.WriteLine("交换前,a 的值:{0}",a);
Console.WriteLine("交换前,b 的值:{0}",b);
/* 调用函数交换值 */
n.swap(ref a, ref b);
Console.WriteLine("交换后,a 的值:{0}",a);
Console.WriteLine("交换后,b 的值:{0}",b);
Console.ReadLine();
}
}
}
输出
交换前,a 的值:100 交换前,b 的值:200 交换后,a 的值:200 交换后,b 的值:100
Out 参数
return 语句只能用于从函数返回一个值。但是,使用 out 参数,您可以从函数返回两个值。
下面是一个例子 −
示例
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void getValue(out int x ) {
int temp = 10;
x = temp;
}
static void Main(string[] args) {
NumberManipulator n = new NumberManipulator();
/* 局部变量定义 */
int a = 150;
Console.WriteLine("方法调用前,a 的值:{0}", a);
/* 调用函数获取值 */
n.getValue(out a);
Console.WriteLine("方法调用后,a 的值:{0}", a);
Console.ReadLine();
}
}
}
输出
方法调用前,a 的值:150 方法调用后,a 的值:10

