class Program
{
static void swap( int a, int b)
{
int c = 0;
c = a;
a = b;
b = c;
}
static void Main(string[] args)
{
int a = 2; int b = 5;
swap( a, b);
Console.WriteLine("a="+a + " and b=" + b);
Console.ReadKey();
}
}
class Program
{
static void swap(ref int a,ref int b)
{
int c = 0;
c = a;
a = b;
b = c;
}
static void Main(string[] args)
{
int a = 2; int b = 5;
swap(ref a,ref b);
Console.WriteLine("a="+a + " and b=" + b);
Console.ReadKey();
}
}
ref int a 的意思就是传递的时候将a的地址传进去,也就是传递的是a的本身(传递引用),此时在swap这个方法运行下,就会对a和b的值进行修改,相应的内存中的值也会改变。那么在输出的时候,a,b的值自然就改变了。
扩展:于ref修饰符类似的修饰符是out
out不用对参数进行初始化,其他的和ref类似。
示例:
class Program
{
static void getValue(out int a,out int b)
{
a = 2; b = 5;
}
static void Main(string[] args)
{
int a; int b;
getValue(out a,out b);
Console.WriteLine("a="+a + " and b=" + b);
Console.ReadKey();
}
}