C# out和ref

C#中默认的参数传递都是值传递,想要使用引用传递就需要使用ref和out关键字,ref和out都是引用传递,但是逻辑上有区别

ref需要初始化参数才能进行传递,逻辑是已经有了,传进来,来帮我改改

out不需要,out的逻辑是不管有没有,传进来,主要给我传出来

例子:

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

namespace study
{
    public class Program
    {
        /// <summary>
        /// ref关键字可以让一个值类型的输入按引用传递,类似于C语言中的&
        /// </summary>
        private static void refFunction(int x,ref int a)
        {
            a = a * x;
        }        
        /// <summary>
        /// out关键字的使用
        /// 使用out关键字,输入参数str在传递给outKeyWord()方法前不必进行初始化
        /// </summary>
        private static void outKeyWord(out string str)
        {
            //输出参数str在方法返回前必须被赋值
            str = "a string";
        }
        static void Main(string[] args)
        {
            //***********ref关键字的使用
            int x = 12, a = 5;
            Console.WriteLine(a);//输出:5
            refFunction(x, ref a);
            Console.WriteLine(a);//输出:60
            
            //***********out关键字的使用
            string str;//不必初始化
            outKeyWord(out str);//输出:a string
            Console.WriteLine(str);
            Console.ReadKey();

        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值