ref与out的举例说明

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

namespace ref和out
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 20;
            int m = 20;//必须先初始化
            int n;// = 20;可以不初始化
            Ex1(i);//复制一份,还是20
            Ex2(ref m);//必须先初始化,内部对外部的值进行改变
            Ex3(out n);//out是从out里取值,内部为外部变量进行赋值,用在多个返回值的场所
            Console.WriteLine(i);
            Console.WriteLine(m);
            Console.WriteLine(n);
            //举例
            int x;
            string y = Console.ReadLine();
            if (int.TryParse(y, out x))//TryParse返回bool
            {
                Console.WriteLine("转换正确,转换值是:{0}", x);
            }
            else
            {
                Console.WriteLine("错误");
            }
            //举例结束
            Console.ReadKey();
        }
        static void Ex1(int i) 
        {
            i++;
        }
        static void Ex2(ref int m)
        {
            m++;
        }
        static void Ex3(out int n) 
        {
            n = 20;//必须为n初始化
            n++;
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值