前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C# ref与out关键字解析

C# ref与out关键字解析

作者头像
郑小超.
发布2018-01-26 11:10:37
4770
发布2018-01-26 11:10:37
举报
文章被收录于专栏:GreenLeavesGreenLeaves

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

1、相同点

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

2、ref关键字

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

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

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

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

(2)、代码示例:

代码语言:javascript
复制
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)、代码示例

代码语言:javascript
复制
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、

代码语言:javascript
复制
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、

代码语言:javascript
复制
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 参数,而另一个方法不采用这两个参数,则可以进行重载

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-05-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档