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

翻译:Visual C# 4.0的新特性-第二部分-命名参数(Names Parameters)

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 

 

 

posted @ 2009-12-04 11:22  CodeYu  阅读(433)  评论(0编辑  收藏  举报