未标明原创的文章皆为转载~

翻译:Visual C# 4.0中的新特性-第一部分-可选参数(Optional parameters)

This is the first blog from a series of blog post which I'm planning to do on whet’s new in Visual C# 4.0

这是我打算写的《Visual C# 4.0中的新特性》系列文章的第一篇。

可选参数(Optional parameters)

Optional parameters is a new feature in C# 4.0 which will let you set a default value for an argument of a method. In case that the collie of the method will omit the argument the default value will take its place.

可选参数(Optional parameters)是C# 4.0的一个新特性,可以为一个方法的参数设置一个默认值。(译者注:为一个参数设置一个默认值,这个参数就是可选参数)一旦被调用的方法忽略可选参数,就会用默认值代替。

So instead of writing the following code:

所以,替换下面的代码:

代码
 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             SaySomething();
 6             SaySomething("Ohad");
 7 
 8             Console.ReadLine();
 9         }
10 
11         public static void SaySomething()
12         {
13             Console.WriteLine("Hi !");
14         }
15 
16         public static void SaySomething(string name)
17         {
18             Console.WriteLine(string.Format("Hi {0}!",name));
19         }
20     }
21 

 

You will only have to write:

你只需要这样写:

 

代码
 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             SaySomething(); //(译者注:等同于SaySomething("");)
 6             SaySomething("Ohad");
 7 
 8             Console.ReadLine();
 9         }
10 
11         public static void SaySomething(string name = "")
12         {
13             Console.WriteLine(string.Format("Hi {0}!",name));
14         }
15     }
16 

 

The statement name = “” at line 11 does the trick of the optional parameter with passing and empty string as the optional parameter.

第11行语句name = “”是可选参数。作用是传递一个空字符串作为选用参数。

Note that some of the reader of this post my think that its better to use string.Empty instead of double quote “” as it normally do but :

注意一些读这篇文章的读者认为用string.Empty比用双引号""更好。但是:

代码
 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             SaySomething();
 6             SaySomething("Ohad");
 7 
 8             Console.ReadLine();
 9         }
10 
11         public static void SaySomething(string name = string.Empty)
12         {
13             Console.WriteLine(string.Format("Hi {0}!",name));
14         }
15     }
16 

 

using string.Empty will result with a compilation error:

用string.Empty将引起一个编译错误:

“Default parameter value for 'name' must be a compile-time constant”

“'name'的默认值应该是一个编译时常量”

And as it string.Empty is not a literal.

而string.Empty不是一个字面值。

posted @ 2009-12-03 23:18  CodeYu  阅读(510)  评论(0编辑  收藏  举报