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

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

问题描述

我正在阅读 Bill Wagner 的Effective C#.在 Item 14 - Minimize Duplicate Initialization Logic 中,他展示了在构造函数中使用新的可选参数功能的以下示例:

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:

public MyClass(int initialCount = 0, string name = "")

注意他使用了 "" 而不是 string.Empty.
他评论:

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

您会注意到 [在上面的示例中] 第二个构造函数指定了"作为 name 参数的默认值,而不是更习惯的 string.Empty.那是因为 string.Empty 不是编译时常量.它是字符串类中定义的静态属性.因为它不是编译常量,所以不能将它用作参数的默认值.

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 几乎没有什么意义,实际上在许多情况下它是一个悲观,因为编译器可以内联一些对 "" 的引用,但不能对 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天全站免登陆