翻譯:Visual C# 4.0的新特性-第二部分-具名引數(Names Parameters)

來源:互聯網
上載者:User

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?"); 

5     Console.ReadLine(); 
6 }

 

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 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.