C# ref与out关键字解析

时间:2022-04-24
本文章向大家介绍C# ref与out关键字解析,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

简介:ref和out是C#开发中经常使用的关键字,所以作为一个.NET开发,必须知道如何使用这两个关键字.

1、相同点

ref和out都是按地址传递,使用后都将改变原来参数的数值。

2、ref关键字

(1)、使用ref关键字的注意点:

i、方法定义和调用方法都必须显式使用 ref 关键字

ii、传递到 ref 参数的参数必须初始化,否则程序会报错

iii、通过ref的这个特性,一定程度上解决了C#中的函数只能有一个返回值的问题

(2)、代码示例:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 6;
            int b = 66;
            Fun(ref a,ref b);
            Console.WriteLine("a:{0},b:{1}", a, b);//输出:72和6说明传入Fun方法是a和b的引用
        }
        static void Fun(ref int a, ref int b) {
            a = a+b;  //72,说明Main方法的a和b的值传进来了
            b = 6;
        }
    }
}

(2)、out关键字

(1)、使用out关键字的注意点:

i、方法定义和调用方法都必须显式使用 out关键字

ii、out关键字无法将参数值传递到out参数所在的方法中,只能传递参数的引用(个人理解),所以out参数的参数值初始化必须在其方法内进行,否则程序会报错

iii、通过out的这个特性,一定程度上解决了C#中的函数只能有一个返回值的问题

(2)、代码示例

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a=100;
            int b;
            Fun(out a, out b);
            Console.WriteLine("a:{0},b:{1}", a, b);//输出:3和1说明out参数传递进去的是a和b的引用,输出3说明a的参数值没有传入Fun方法中
        }
        static void Fun(out int a, out int b)
        {
            a = 1+2;
            b = 1;
        }
    }
}

(3)、ref和out的区别

通过上面的解析,ref和out最主要的区别是:

ref将参数的参数值和引用都传入方法中,所以ref的参数的初始化必须在方法外部,进行,也就是ref的参数必须有初始化值,否则程序会报错

out不会将参数的参数值传入方法中,只会将参数的引用传入方法中,所以参数的初始化工作必须在其对用方法中进行,否则程序会报错

(4)、ref和out的使用需注意

i、

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

namespace ConsoleApplication1
{
    class Program
    {

        public void SampleMethod(ref int i) { }
        public void SampleMethod(out int i) { }

    }
}

尽管 ref 和 out 在运行时的处理方式不同,但在编译时的处理方式相同。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个方法是完全相同的,因此将不会编译上面的代码

ii、

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

namespace ConsoleApplication1
{
    class Program
    {
        public void SampleMethod(int i) { }
        public void SampleMethod(ref int i) { }
    }
}

但是,如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两个参数,则可以进行重载