您的位置:首页 > 编程语言 > C#

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

2009-12-03 23:18 316 查看
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(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不是一个字面值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐