关于ref和out

方法参数上的 ref 关键字使方法引用传递到方法的同一个变量。当控制传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。若要使用 ref 参数,必须将参数作为 ref 参数显式传递到方法。ref 参数的值被传递到 ref 参数。

传递到 ref 参数的参数必须最先初始化。将此方法与 out 参数相比,后者的参数在传递到 out 参数之前不必显式初始化。

属性不是变量,不能作为 ref 参数传递。

如果两种方法的声明仅在它们对 ref 的使用方面不同,则将出现重载。但是,无法定义仅在 refout 方面不同的重载。例如,以下重载声明是有效的:

class MyClass 
{
   public void MyMethod(int i) {i = 10;}
   public void MyMethod(ref int i) {i = 10;}
}

但以下重载声明是无效的:

class MyClass 
{
   public void MyMethod(out int i) {i = 10;}
   public void MyMethod(ref int i) {i = 10;}
}
// cs_ref.cs
using System;
public class MyClass
{
   public static void TestRef(ref char i)
   {
      // The value of i will be changed in the calling method
      i = 'b';
   }

   public static void TestNoRef(char i)
   {
      // The value of i will be unchanged in the calling method
      i = 'c';
   }

   // This method passes a variable as a ref parameter; the value of the
   // variable is changed after control passes back to this method.
   // The same variable is passed as a value parameter; the value of the
   // variable is unchanged after control is passed back to this method.
   public static void Main()
   {
  
      char i = 'a';    // variable must be initialized
      TestRef(ref i);  // the arg must be passed as ref
      Console.WriteLine(i);
      TestNoRef(i);
      Console.WriteLine(i);
   }
}
输出

b
b

方法参数out 关键字使方法引用传递到方法的同一个变量。当控制传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。当希望方法返回多个值时,声明 out 方法非常有用。使用 out 参数的方法仍然可以返回一个值。一个方法可以有一个以上的 out 参数。

若要使用 out 参数,必须将参数作为 out 参数显式传递到方法。out 参数的值不会传递到 out 参数。不必初始化作为 out 参数传递的变量。然而,必须在方法返回之前为 out 参数赋值。属性不是变量,不能作为 out 参数传递。

如果两个方法的声明仅在 out 的使用方面不同,则会发生重载。不过,无法定义仅在 refout 方面不同的重载。例如,以下重载声明是有效的:

class MyClass 
{
   public void MyMethod(int i) {i = 10;}
   public void MyMethod(out int i) {i = 10;}
}

而以下重载声明是无效的:

class MyClass 
{
   public void MyMethod(out int i) {i = 10;}
   public void MyMethod(ref int i) {i = 10;}
}
// example:cs_out.cs 
using System;
public class MyClass 
{
   public static int TestOut(out char i) 
   {
      i = 'b';
      return -1;
   }

   public static void Main() 
   {
      char i;   // variable need not be initialized
      Console.WriteLine(TestOut(out i));
      Console.WriteLine(i);
   }
}
输出
-1
b
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值