C# 参数默认值和命名参数
[ C# 4.0/.NET 4.0 新增特性 ]
3.1 带默认值的方法
static void Main(string[] args) { // 01.带默认值参数函数 FuncWithDefaultPara(); // 02.省略一个默认参数调用 FuncWithDefaultPara(10086); Console.ReadKey(); } static void FuncWithDefaultPara(int id = 10010, bool gender = true) { Console.WriteLine("Id:{0},Gender:{1}", id, gender ? "Man" : "Woman"); }
点击调试,显示结果如下:
3.2 编译后的方法调用
同样,为了一探带参数默认值方法调用的细节,我们还是借助反编译神器查看其中的玄妙:
(1)首先,我们来看看带默认值参数的方法被编译后是怎么的:
可以看到,在.NET Framework中大量采用了基于Attribute的开发方式,这里为参数添加了表示默认值的特性DefaultParameterValue。
(2)其次,再来看看Main函数中的调用过程是怎么被编译的:
可以看出,编译器帮我们在方法调用的括号中帮我们填充了默认值。这里,我们不禁好奇,如果在调用中,不指定ID(即使用ID默认值10010)而仅仅指定Gender为false是否可以编译通过?我们来试一下:
static void Main(string[] args) { // 01.带默认值参数函数 FuncWithDefaultPara(); // 02.省略一个默认参数调用 FuncWithDefaultPara(10086); // 错误调用: FuncWithDefaultPara(false); Console.ReadKey(); }
这时,出现了以下错误:
于是,我们知道,CSC也还没有那么智能,无法理解我们高深的“意图”。那么,有木有一种方法来解决这种需求呢,于是命名参数横空出世了。
3.3 使用命名参数
在新语法中为方法调用引入了命名参数,格式为 参数名:参数值
static void Main(string[] args) { // 01.带默认值参数函数 FuncWithDefaultPara(); // 02.省略一个默认参数调用 FuncWithDefaultPara(10086); // 错误调用: //FuncWithDefaultPara(false); // 03.使用命名参数调用 FuncWithDefaultPara(gender: false); Console.ReadKey(); }
通过调试,可以得到如下结果:
通过前面的分析,我们可以分析出,使用命名参数被编译之后还是会生成指定参数值的调用:
出处:http://edisonchou.cnblogs.com