不能使用的String.Empty作为默认值的可选参数 [英] Cannot use String.Empty as a default value for an optional parameter

查看:204
本文介绍了不能使用的String.Empty作为默认值的可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读有效的C#由比尔·瓦格纳。在项目14 - 最大限度地减少重复初始化逻辑的,他显示了使用新的可选参数,下面的例子在构造函数功能:

I am reading Effective C# by Bill Wagner. In Item 14 - Minimize Duplicate Initialization Logic, he shows the following example of using the new optional parameters feature in a constructor:

公共MyClass的(INT initialCount = 0,字符串名称=)

注意,他用而不是的String.Empty 。结果
他评论道:

Notice that he used "" instead of string.Empty.
He comments:

您会注意到[在上面的示例]该规定,关于名称的默认值第二个构造的参数,而不是更习惯的String.Empty 。这是因为的String.Empty 是不是编译时间常数。它是在String类中定义的静态属性。因为它不是一个编译常数,你不能用它为一个参数的默认值。

You'll note [in an example above] that the second constructor specified "" for the default value on the name parameter, rather than the more customary string.Empty. That's because string.Empty is not a compile-time constant. It is a static property defined in the string class. Because it is not a compile constant, you cannot use it for the default value for a parameter.

如果我们不能使用的String.Empty 静在所有情况下,则并不认为战胜它的目的是什么?我以为,我们会用它来确保我们指的是空字符串独立于系统的手段。我的理解是错误的?谢谢你。

If we cannot use the string.Empty static in all situations, then doesn't that defeat the purpose of it? I thought that we would use it to be sure that we have a system-independent means of referring to the empty string. Is my understanding wrong? Thanks.

更新结果
只是跟进评论。根据MSDN:

UPDATE
Just a follow up comment. According to MSDN:

每个可选参数有一个默认值作为其定义的一部分。如果没有参数为该参数发送,则使用默认值。 默认值必须是常量。

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. Default values must be constants.

那么我们是不是可以使用 System.Environment.NewLine 要么,或使用新实例化对象为默认值。我没有用VS2010的是,这是令人失望的!

Then we aren't be able to use System.Environment.NewLine either, or use newly instantiated objects as default values. I haven't used VS2010 yet, and this is disappointing!

推荐答案

由于C#2.0编译器,很少有指向的String.Empty ,无论如何,在事实上,在许多情况下,这是一个pessimisation,因为编译器可以内联到一些参考,但不能做同样的的String.Empty

As of the C# 2.0 compiler, there is very little point to String.Empty anyway, and in fact in many cases it's a pessimisation, since the compiler can inline some references to "" but can't do the same with String.Empty.

在C#1.1它是有用的,以避免产生大量独立的对象都包含空字符串,但那些日子已经一去不复返了。 作品就好。

In C# 1.1 it was useful to avoid creating lots of independent objects all containing the empty string, but those days are gone. "" works just fine.

这篇关于不能使用的String.Empty作为默认值的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆