C#按引用传递参数
与按值传递参数,实参和形参使用的是两个不同内存中的值不同,按引用传递参数,引用参数是一个对变量的内存位置的引用,不会创建新的存储位置。
按引用传递参数的使用方式是在方法声明和引用时在传参前加ref修饰
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(ref int x, ref int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
int a = 100;
int b = 200;
Console.WriteLine("在交换前,a、b的值:{0}、{1}",a,b);
n.swap(ref a,ref b);
Console.WriteLine("在交换后,a、b的值:{0}、{1}", a, b);
Console.ReadLine();
}
}
}
这个历程中打印结果:
在交换前,a、b的值:100、200
在交换后,a、b的值:200、100