C#编程函数参数传递中out修饰符的作用
1、打开vs2015开发工具,点击菜单栏的文件 -- 新建 -- 项目,新建一个控制台项目来测试函数参数传递时out修饰符的作用。
2、在项目入口文件Program.cs文件中写代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace COut
{
class Program
{
static void Main(string[] args)
{
string name;
int id;
bool b = Test(name,id);
}
static bool Test(string name,int id)
{
name = "张三";
id = 1;
return true;
}
}
}
这里使用的Test函数接收不带out修饰的两个变量参数,name和id,在入口函数中声明了这两个变量但是没有赋值。
3、点击运行按钮,运行代码,这时时会报错的,因为变量在参数传递前没有初始化,即没有赋值操作。
4、修改代码如下,在参数传递时使用out修饰,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace COut
{
class Program
{
static void Main(string[] args)
{
string name;
int id;
bool b = Test(out name,out id);
Console.ReadKey();
}
static bool Test(out string name,out int id)
{
name = "张三";
id = 1;
return true;
}
}
}
5、再次点击运行按钮,运行代码就没有报错了,也就是说使用了out来修饰传递的参数,就不需要提前赋值给变量了。
6、实际上如果用了out修饰参数,即使我们在参数传递前给变量赋值了,也必须在函数里再次赋值。例如下面代码是会报错的。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace COut
{
class Program
{
static void Main(string[] args)
{
string name = "李四";
int id = 2;
bool b = Test(out name,out id);
Console.ReadKey();
}
static bool Test(out string name,out int id)
{
// name = "张三";
// id = 1;
return true;
}
}
}
7、修改代码,测试out修饰,可以类似使用多返回值的功能,打印出out修饰的变量,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace COut
{
class Program
{
static void Main(string[] args)
{
string name;
int id;
bool b = Test(out name,out id);
Console.WriteLine(name);
Console.WriteLine(id);
Console.WriteLine(b);
Console.ReadKey();
}
static bool Test(out string name,out int id)
{
name = "张三";
id = 1;
return true;
}
}
}
8、点击运行,运行代码成功打印出两个out修饰参数和Test函数本身的返回值,这是out修饰最常用的功能。