C#函数的高级参数-- ref引用型形参

任务描述

本关任务:编写一个能交换两数的小程序。

相关知识

引用类型ref与out的区别

  1. 引用类型传的是地址,值类型传的是值。ref和out都是引用类型。
  2. ref把参数的数值传递进函数,因此要求ref参数在进函数之前必须初始化值。
  3. out进函数后,首先把out参数清空,所以在函数中必须初始化一次out参数。
string uid = "admin";//必须赋初始值  
string pwd = "777777";//必须赋初始值       
string msg;                   
ModifyUser(ref uid, ref pwd, out msg)  
.....
public static bool ModifyUser(ref string uid, ref string pwd, out string msg)  
{  
    ....  
    msg="成功" //必须有一句,是给msg赋值  
    ....  
}  

通俗点说:ref是有进有出,out是只出不进。

编程要求

根据提示,在右侧编辑器补充代码,用方法实现两个整数的互换。

测试说明
平台会对你编写的代码进行测试:

测试输入:4,91
预期输出:91,4

代码

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

namespace program08
{
    class Program08
    {

        static void Main(string[] args)
        {
            int n1, n2;
            int.TryParse(Console.ReadLine(), out n1);
            int.TryParse(Console.ReadLine(), out n2);
            ExchangeFunc(ref n1, ref n2);
            Console.WriteLine("{0},{1}", n1, n2);
            Console.ReadKey();
        }
        //begin
        //编写public static void ExchangeFunc交换方法
        public static void ExchangeFunc( ref int n1, ref int n2)
        {
            int p = n1;
            n1 = n2;
            n2 = p;
        }
        
        //end 
    }
}

题目链接

链接: ref引用型形参.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值