技术开发 频道

细数C# 4.0四大新特性(代码示例)

  3.方法参数之可选参数

  如下方法声明的语法

static void DoSomething(int notOptionalArg,string arg1 = "default Arg1", string arg2 = "default arg2") { Console.WriteLine("arg1 = {0},arg2 = {1}",arg1,arg2); }

这个方法有三个参数第一个是必选参数,第二个和第三个是可选参数,他们都有一个默认值。这种形式对固定参数的几个方法重载很有用。如下调用:

static void Main(string[] args) { DoSomething(1); DoSomething(1, "葫芦"); DoSomething(1, "葫芦", "黄瓜"); Console.ReadLine(); }

也许你会想到,假如我有一个和可选参数方法不选某个参数相同的方法签名的方法时,C#会怎么处理呢,我们看下下面的代码

static void DoSomething(int notOpArg, string arg) { Console.WriteLine("arg1 = {0}", arg); } 这里又重载了一个DoSomething

这个方法有两个参数,但是没有可选参数,实验证明调用DoSomething(1,”arg”)时会优先执行没有可选参数的方法。

  4.方法参数之命名参数

static void DoSomething(int height, int width, string openerName, string scroll) { Console.WriteLine("height = {0},width = {1},openerName = {2}, scroll = {3}",height,width,openerName,scroll); }

命名参数让我们可以在调用方法时指定参数名字来给参数赋值,这种情况下可以忽略参数的顺序。如下方法声明:

  我们可以这样来调用上面声明的方法

static void Main(string[] args) { DoSomething( scroll : "no",height : 10, width : 5, openerName : "windowname"); Console.ReadLine(); }

很显然的这是一个语法糖,但是在方法参数很多的情况下很有意义,可以增加代码的可读性。

0