ref 和out 到底有什么差别

本文对比了C#中的ref和Out关键字,指出它们在函数参数传递上的差异:ref允许在函数内部修改变量,类似引用;Out则需先声明后使用,功能更像返回值。通过代码实例和运行结果,详细阐述了两者的使用场景和行为.
摘要由CSDN通过智能技术生成

1.概要

ref 和out 到底有什么差别,从使用的角度其实差别不大。唯一不同的是,out在函数内初始化,而ref必须在函数外部初始化。Out的功能更想是真正的返回值。而ref更像是引用的变量。1.

2.代码

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

namespace ref和Out的差别
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("ref和Out的差别");
            Program program = new Program();
            program.main();
            Console.ReadKey();
        }
        private void main() {
            Ref @ref = new Ref();
            @ref.test();
            Out @out = new Out();
            @out.test();
        }
        class Ref {
            public void test()
            {
                //int a;//err 使用了为赋值的局部变量
                int a = 0;
                testRef(ref a);
                Console.WriteLine("值:" + a);
            }
            private void testRef(ref int a)
            {
                a = 5;
            }
        }
        class Out {
            public void test()
            {
                int a;
                testOut(out a);
                Console.WriteLine("值:" + a);
            }
            private void testOut(out int a)
            {
                a = 5;
            }
        }
    }
}

3.运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值