任务描述
本关任务:编写一个能交换两数的小程序。
相关知识
引用类型ref与out的区别
- 引用类型传的是地址,值类型传的是值。ref和out都是引用类型。
- ref把参数的数值传递进函数,因此要求ref参数在进函数之前必须初始化值。
- 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引用型形参.