0
点赞
收藏
分享

微信扫一扫

C#(四):ref 和 out

成义随笔 2022-07-14 阅读 59


​ref​​​ 和 ​​out​

  • ​ref​
  • 用来修饰参数
  • 如果一个形参用​​ref​​​修饰,那么实参也需要用​​ref​​修饰
  • ​a​​​的改变是因为用​​ref​​​修饰的参数最终传的是实参的​​地址​

public static void Change(ref int x) {
x = 20;
}

int a = 10;
Change(ref a);
Console.WriteLine(a); // 20

  • ​out​
  • 用来修饰参数
  • 如果一个形参用​​out​​​修饰,那么实参也需要用​​out​​修饰
  • ​a​​​的改变是因为用​​out​​​修饰的参数最终传的是实参的​​地址​

public static void Change(out int x)
{
x = 20;
}

Change(out int a);
Console.WriteLine(a);

  • 区别
  • 在方法结束之前必须对​​out​​参数赋值

public static void Change(out int x) { } // Error 没有对参数x进行赋值

  • ​ref​​​参数可以直接使用,而​​out​​​参数需要进行赋值后才能使用(​​ref参数默认被赋值了而out参数默认没有被赋值​​)

public static void Change(ref int x)
{
Console.WriteLine(x); // ok
}

public static void Change(out int x)
{
Console.WriteLine(x); // Error 使用了未赋值的变量x
x = 20;
Console.WriteLine(x); // ok
}


举报

相关推荐

0 条评论