关键字out,关键字ref

 

 
class RefExample
{
    static void Method(ref int i)
    {
        i = 44;
    }
    static void Main()
    {
        int val = 0;
        Method(ref val);
        // val is now 44
    }
}
 
 
 
class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}
 
  
  
 
 
一看就明白,out和ref都是引用传值,不同之处就是使用ref传变量的时候,这个变量必须是经过初始化的
而out就没有这个限制!  但是out还是有一个限制的,就是在传递之前不需要付值,但传递给方法之后,该
方法必须要给改变量付值。
 
  
  
 
 
下面引用msdn的一句话:
ref 和 out 关键字在运行时的处理方式不同,但在编译时的处理方式相同。因此,如果一个方法采用 ref 
参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个
方法是完全相同的,因此将不会编译以下代码:
class CS0663_Example 
{
    // compiler error CS0663: "cannot define overloaded 
    // methods that differ only on ref and out"
    public void SampleMethod(out int i) {  }
    public void SampleMethod(ref int i) {  }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值