using System;
using System.Collections.Generic;
using System.Text;namespace reference
{
class Program
{ static void Swarp(ref int x,ref int y)
{
int type = x;
x = y;
y = type;
}
static void Main()
{
int i = 1;
int j = 2;
Swarp(ref i, ref j);
Console.WriteLine("i={0},j={1}", i, j);
Console.Read(); }
}
}谁能帮我具体点解释一下这个代码么?
using System.Collections.Generic;
using System.Text;namespace reference
{
class Program
{ static void Swarp(ref int x,ref int y)
{
int type = x;
x = y;
y = type;
}
static void Main()
{
int i = 1;
int j = 2;
Swarp(ref i, ref j);
Console.WriteLine("i={0},j={1}", i, j);
Console.Read(); }
}
}谁能帮我具体点解释一下这个代码么?
参数必须用ref,地址传递方式才能起到交换的作用。
默认的值传递是复制。
int i = 1;
int j = 2;
运行后
int i = 2;
int j = 1;
如果不用ref
int i = 1;
int j = 2;
对你的程序而言变量i,j对应x,y,也就是x,y的改变,i,j也改变,
调用Swarp函数后,i=x,j=y!
事实上是读相同的一块内存区域
ref out 修饰后 形参和实参是一个东西
形参改变了 实参也改变
ref传参 之前要初始化
他会默认再申请新的内存空间给你的x,y,也就是把i,j复制,
但当你加上ref 的时候,传递的只是内存的地址,操作还是对
同一块内存,也就是说,你改变了x,y,原来的i.j也就变了
有两种数据类型 值类型,和引用类型,对于值类型默认是通过值值类型传递, 引用类型默认自然就是按引用类型传递
(不过string 这个引用类型默认是按值类型传递的)
static void Swarp(ref int x,ref int y)
用下面这种函数调用完了传入的x,y是不发生变化的
static void Swarp( int x, int y)