C# ref out的使用与区别

484 阅读2分钟

Ref 和 out可以理解为类似的传址引用。

在函数需要外部传入一个变量名,然后在程序内部可以将这个值进行修改,典型的传址引用!在定义时必要加ref或out说明!

Ref和Out的区别:

ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。

out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。若要使用 out 参数,方法定义和调用方法都必须显式使用 out 关键字。 


Ref型参数引入前必须赋值。

Out型参数引入前不需赋值,赋值也没用。

定义一个refs类中含有ref和out方法:

public class Refs
    {
        /// <summary>
        /// out 关键字
        /// </summary>
        public void outArea(int r_width, int r_height, out int r_area)
        {
            r_area = r_width * r_height;
       
        }
 
        /// <summary>
        /// ref 关键字
        /// </summary>
        public void refArea(int r_width,int r_height, ref int o_area)
        {
            o_area = r_width * r_height;
        }
 
    }

实例化调用:

Refs rs = new Refs();
            rs.outArea(r_width, r_height, out r_area);
 
            Console.WriteLine(r_area);  // 输出200
 
            int o_area = 0;
            rs.refArea(r_width,r_height,ref o_area);
 
            Console.WriteLine(o_area);  // 输出200

测试使用全部代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace refOut
{
    public class Program
    {
        static void Main(string[] args)
        {
            // 求长方形面积
            int r_width = 10;
            int r_height = 20;
            int r_area = 0;
            Refs rs = new Refs();
            rs.outArea(r_width, r_height, out r_area);
            Console.WriteLine(r_area);  // 输出200
            int o_area = 0;
            rs.refArea(r_width,r_height,ref o_area);
            Console.WriteLine(o_area);  // 输出200
            Console.ReadKey();
        }
    }
    public class Refs
    {
        /// <summary>
        /// out 关键字
        /// </summary>
        public void outArea(int r_width, int r_height, out int r_area)
        {
            r_area = r_width * r_height;
       
        }
        /// <summary>
        /// ref 关键字
        /// </summary>
        public void refArea(int r_width,int r_height, ref int o_area)
        {
            o_area = r_width * r_height;
        }
    }
}

ref,out关键字在平时开发中我还真没有用过,这个还是在leetcode里边刷题的时候遇到的。每个语言都有其独到的地方,但是这些东西,大同小异吧。

有好的建议,请在下方输入你的评论。

欢迎访问个人博客 guanchao.site

欢迎访问小程序:

在这里插入图片描述