C# 中的 ref 和 out 的意义和使用方法

        向方法传递一个实参时,对应的形参会用实参的一个副本来初始化,不管形参是值类型(例如 int),可空类型(int?),还是引用类型,这一点都是成立的。也就是随便在方法内部进行什么修改,都不会影响实参的值。例如,对于引用类型,方法的改变,只是会改变引用的数据,但实参本身并没有变化,它仍然引用同一个对象。

        代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ref_out
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 8;
            Console.WriteLine(i);
            DoIncrease(i);
            Console.WriteLine(i);
        }

        static void DoIncrease(int a)
        {
            a++;
        }
    }
}
        运行结果如下:



        若使用 ref 关键字,向形参应用的任何操作都同样应用于实参,因为形参和实参引用的是同一个对象。PS:实参和形参都必须附加 ref 关键字做为前缀。

        代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ref_out
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 8;
            Console.WriteLine(i);   // 8
            DoIncrease(ref i);      // 实参前也必须加 ref
            Console.WriteLine(i);   // 9 // ref 关键字使对形参的动作也应用于实参
        }

        static void DoIncrease(ref int a)   // 形参前必须加 ref
        {
            a++;
        }
    }
}
        运行结果如下:

        ref 实参使用前也必须初始化,否则不能通过编译。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ref_out
{
    class Program
    {
        static void Main(string[] args)
        {
            int i;          // ref 实参没有初始化,所以程序不能通过编译
            Console.WriteLine(i);
            DoIncrease(ref i);
            Console.WriteLine(i);
        }

        static void DoIncrease(ref int a)
        {
            a++;
        }
    }
}

        有时我们希望由方法本身来初始化参数,这时可以使用 out 参数。

        代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ref_out
{
    class Program
    {
        static void Main(string[] args)
        {
            int i;    // 没有初始化
            //Console.WriteLine(i); // 此处 i 未初始化,编译错误
            DoIncrease(out i);  // 用方法来给实参赋初值
            Console.WriteLine(i);
        }

        static void DoIncrease(out int a)
        {
            a = 8;  // 在方法中进行初始化
            a++;    // a = 9
        }
    }
}
        运行结果如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值