一 ref:refence引用
ref把值类型转换为引用类型,ref修饰的参数必须显式存在,举例,进行数字交换程序书写:
public void Exchange(int a,int b) //在方法中定义局部变量X,Y,单独开辟一个地址
{
int temp ;
temp = a;
a =b;
b = temp;
}
static void Main(string[] args)
{
int x = 1; //xy定义局部变量,同样是单独开辟地址
int y = 2;
new Program().Exchange(x,y); //函数中参数传递只是把内容传递到方法对应地址中,没有更改该函数中局部变量x,y的值
Console.WriteLine( $"x={x},y={y}" );
}
打印结果:
x=1,y=2
以上没有满足数字交换的需求,把内容传递到对应地址中,则需要用ref修饰,把x,y的地址传递到方法中更改程序如下:
public void Exchange(ref int a,ref int b)
{
int temp ;
temp = a;
a =b;
b = temp;
}
static void Main(string[] args)
{
int x = 1;
int y = 2;
new Program().Exchange(ref x,ref y); //在函数调用时,必须加上ref,相当于把x,y的地址传递给a,b
Console.WriteLine( $"x={x},y={y}" );
}
打印结果:
x=2,y=1
使用ref修饰实参时,则必须进行先赋值:
public void add(int a, int b, ref int resut)
{
resut = a+b;
}
static void Main(string[] args)
{
int x = 1;
int y = 2;
int result = 0; //必须进行赋值,否则报错
new Program().add( x, y,ref result);//x,y为 add方法中形参,result为main中实参
Console.WriteLine($"x={x},y={y},result={result}");
}
打印结果:
x=1,y=2,result=3
二 out关键字:
out修饰参数表示把值类型转换为引用类型,用out修饰,则实际参数可以不必赋值,更改ref代码:
public void add(int a, int b, out int resut)
{
resut = a+b; //out修饰的result必须在方法中赋值
}
static void Main(string[] args)
{
int x = 1;
int y = 2;
int result;/int result=0; //可以不进行进行赋值
new Program().add( x, y,out result);//x,y为 add方法中形参,result为main中实参
Console.WriteLine($"x={x},y={y},result={result}");
}
打印结果:
x=1,y=2,result=3
out关键字修饰的参数,在方法中必须进行赋值
三 in关键字
in关键字同样时把值类型转换为引用类型传递参数的地址,和out区别在于,in必须在主函数中进行赋值,在方法中不能赋值
public int add(int a, int b, in int resut)
{
return a+b; //报错,在方法中不能赋值
}
static void Main(string[] args)
{
int x = 1;
int y = 2;
int result=1000; //必须在调用前进行赋值
new Program().add( x, y,in result);
Console.WriteLine($"x+y={new Program().add( x, y,in result)},result={result}");
}
打印结果:
x+y=3,result=1000
四:ref,out,in特性
共同点:将值类型转换为引用类型(按照地址传值)
区别:in无法修改变量的值,ref在调用方法前必须进行赋值,在方法中也可以修改值(有进有出)
out修饰:在方法中必须赋值,在调用前可以不用赋值,(只出不进.)