C#简单的分析 ref 与out的使用

首先在项目中的使用,注意事项。

主要是ref 能够把参数原本值带进函数内,经过一些运算,然后再带出去。(注意参数的值必须在调用之前赋值)

out是先把参数没有进行赋值,带进函数内,首先要经过赋值,接着经过一些运算,然后在带出去。(注意参数的值必须在内部先进行赋值,再操作)

简单的叙述,ref有进有出,out只出不进。

下面是一个简单的举例:

  static void Main(string[] args)
        {
            int f = 10 ;
           ExampleOut(out f);
           Console.WriteLine(f);//此时输出f值为8
           ExampleRef(ref f);
           Console.WriteLine(f);//此时输出f值为9
           Console.ReadLine();
           
          
        }
        public static void ExampleOut(out int  i)
        {

            i=8;//如果不赋值的话,则会报错。
        }
        public static void ExampleRef(ref int i) {
            i++;
        }

再接着写一点,关于类的内部函数重载的注意事项
如果仅是以out,ref做为函数重载的条件化,则会报错。(错误信息:错误 1 无法定义重载方法“Example”,因为它与其他方法仅在 ref 和 out 上有差别)
如下面的例子:
 static void Main(string[] args)
        {
            int f ;
           Example(out f);
           Console.WriteLine(f);
         
           Example(ref f);
           Console.WriteLine(f);
           Console.ReadLine();
           
        }
        public static void Example(out int  i)
        {
            i=8;
        }
        public static void Example(ref int i) {
            i++;
        }

请看下面正确的例子。如 果一个方法采用 ref out 参数,而另一个方法不采用这两个参数,则可以进行重载
  static void Main(string[] args)
        {
            int f =1;
           Example( f);
           Console.WriteLine(f);
         
           Example(ref f);
           Console.WriteLine(f);
           Console.ReadLine();
           
        }
        public static void Example(int  i)
        {
            i=8;
        }
        public static void Example(ref int i) {
            i++;
        }

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值