C# - 按值传递参数
这是向方法传递参数的默认机制。在此机制下,调用方法时,会为每个值参数创建一个新的存储位置。
实际参数的值会被复制到这些值中。因此,在方法内部对参数所做的更改不会影响实参。以下示例演示了此概念 -
using System;
namespace CalculatorApplication {
class NumberManipulator {
public void swap(int x, 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(a, b);
Console.WriteLine("交换后,a 的值:{0}", a);
Console.WriteLine("交换后,b 的值:{0}", b);
Console.ReadLine();
}
}
}
当编译并执行上述代码时,会产生以下结果 -
交换前,a 的值:100 交换前,b 的值:200 交换后,a的值:100 交换后,b的值为:200
它表明虽然函数内部的值已经改变,但值却没有改变。

csharp_methods.html