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 = “”是選擇性參數。作用是傳遞一個Null 字元串作為選用參數。
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不是一個字面值。