参数传递
当调用带有参数的方法时,需要向方法传递参数。在 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("swap before, a: {0}", a);
Console.WriteLine("swap before, b: {0}", b);
/* 调用函数来交换值 */
n.swap(a, b);
Console.WriteLine("swap after, a: {0}", a);
Console.WriteLine("swap after, b: {0}", b);
}
}
}
引用参数传递要使用 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("swap before, a : {0}", a);
Console.WriteLine("swap before, b : {0}", b);
/* 调用函数来交换值 */
n.swap(ref a, ref b);
Console.WriteLine("swap after, a: {0}", a);
Console.WriteLine("swap after, b: {0}", b);
}
}
}