This is the second post of what’s new in Visual Studio C# 4.0.
這是《Visual Studio C# 4.0的新特性》系列的第二篇文章。
At the former post we reviewed the feature of optional parameters at this post we will concentrate on Named Parameters.
在上一篇文章我們瞭解了具名引數(optional parameters)的特性,這篇文章我們來談談具名引數(Named Parameters)。
具名引數(Named Parameters)
Lets assume you are writing the following procedure :
假設你在寫下面這個方法:
public static void SaySomething(string name, string msg)
{
Console.WriteLine(string.Format("Hi {0} !\n{1}", name,msg));
}
When you want to call it from your code you are using something like:
你像下面的方式調用它:
1 static void Main(string[] args)
2 {
3 SaySomething("Ohad","What's up?");
4
5 Console.ReadLine();
6 }
7
What’s the problem ?
有什麼問題?
Although you will have intellisense while you are coding it for the reader of the code its unclear what is the first parameter and what is the second parameter.
儘管有智能提示協助你編寫代碼,但是閱讀代碼的人不清楚第一個參數是什麼,第二個參數是什麼。
This is where Named Parameters gets into the picture. Using named parameter the code becomes much more readable to one who haven’t wrote it.
這正是具名引數(Named Parameters)的用武之地。用具名引數後代碼的可讀性比以前更好。
代碼
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 SaySomething(name: "Ohad", msg: "What's up?");
6
7 Console.ReadLine();
8 }
9
10 public static void SaySomething(string name, string msg)
11 {
12 Console.WriteLine(string.Format("Hi {0} !\n{1}", name,msg));
13 }
14 }
15
Named parameters are specially useful whenever you have multiple optional parameters of the same type. Without using named parameter how would the compiler know if the parameter which is being passed by line 5 is the name or the message.
當你的方法有多個同一類型的選擇性參數(optional parameters)時,具名引數(Named parameters)特別有用。如果不用具名引數,編譯器怎麼知道下面第5行傳遞的參數是name還是message:
代碼
1 class Progra
2 {
3 static void Main(string[] args)
4 {
5 SaySomething(name: "Ohad");
6
7 Console.ReadLine();
8 }
9
10 public static void SaySomething(string name = "Tirza", string msg = "Hi There")
11 {
12 Console.WriteLine(string.Format("Hi {0} !\n{1}", name,msg));
13 }
14 }
15