无法使用 String.Empty 作为可选参数的默认值

发布于 2024-08-30 05:31:55 字数 813 浏览 4 评论 0原文

我正在阅读 Bill Wagner 的Effective C#。在第 14 项 - 最小化重复初始化逻辑中,他展示了在构造函数中使用新的可选参数功能的以下示例:

public MyClass(int initialCount = 0, string name = "")< /code>

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

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

如果我们不能在所有情况下使用 string.Empty 静态,那么这不是违背了它的目的吗?我认为我们会使用它来确保我们有一种独立于系统的方法来引用空字符串。我的理解有错吗?谢谢。

更新
只是后续评论。根据 MSDN:

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

那么我们就无法使用System.Environment.NewLine,也无法使用新实例化的对象作为默认值。我还没有使用过 VS2010,这令人失望!

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 = "")

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

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.

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.

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.

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

听风念你 2024-09-06 05:31:55

从 C# 2.0 编译器开始,String.Empty 无论如何都没有什么意义,事实上在许多情况下这是一种悲观,因为编译器可以内联一些对 "" 的引用code> 但不能对 String.Empty 执行相同操作。

在 C# 1.1 中,避免创建大量包含空字符串的独立对象很有用,但那些日子已经一去不复返了。 "" 工作得很好。

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.

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.

£冰雨忧蓝° 2024-09-06 05:31:55

如果您确实想将空字符串用作可选参数值,那么没有什么可以阻止您为空字符串定义自己的常量:

const string String_Empty = "";

public static void PrintString(string s = String_Empty)
{
    Console.WriteLine(s);
}

[顺便说一句,比 更喜欢 String.Empty 的一个原因一般来说,其他答案中没有提到的是,有各种肉眼看不见的 Unicode 字符(零宽度连接符等)。因此,看起来像 "" 的东西不一定是空字符串,而使用 String.Empty 你可以确切地知道你正在使用什么。我认识到这不是常见的错误来源,但有可能。]

There's nothing to stop you from defining your own constant for the empty string if you really want to use it as an optional parameter value:

const string String_Empty = "";

public static void PrintString(string s = String_Empty)
{
    Console.WriteLine(s);
}

[As an aside, one reason to prefer String.Empty over "" in general, that hasn't been mentioned in the other answers, is that there are various Unicode characters (zero-width joiners, etc.) that are effectively invisible to the naked eye. So something that looks like "" isn't necessarily the empty string, whereas with String.Empty you know exactly what you're using. I recognise this isn't a common source of bugs, but it is possible.]

椒妓 2024-09-06 05:31:55

从原来的问题来看:

我认为我们会使用它来确保我们有一种独立于系统的方法来引用空字符串。

不同系统的空字符串有何不同?它始终是一个没有字符的字符串!如果我发现 string.Empty == "" 返回 false 的实现,我会真的感到害怕:)这是相同的例如Environment.NewLine

来自《反恐精英》的赏金帖子:

我希望 String.Empty 可以在下一个 C# 版本中用作默认参数。 :D

嗯,这肯定不会发生。

虽然我个人也喜欢一种非常不同的默认机制,但可选参数的工作方式从一开始就在 .NET 中 - 并且它总是意味着将常量嵌入到元数据中,以便调用代码可以将该常量复制到调用中如果没有提供相应的参数,则为站点。

使用 string.Empty ,它真的毫无意义 - 使用 "" 会做你想做的事;使用字符串文字是不是很痛苦? (我到处都使用文字 - 我从不使用 string.Empty - 但这是一个不同的论点。)

这就是这个问题让我感到惊讶的地方 - 投诉围绕着一些不的事情展开em> 实际上会造成真正的问题。当您希望在执行时计算默认值时,这一点更为重要,因为它实际上可能会有所不同。例如,我可以想象您希望能够使用 DateTime 参数调用方法并将其默认为“当前时间”的情况。目前,我所知道的唯一隐约优雅的解决方法是:

public void RecordTime(string message, DateTime? dateTime = null)
{
    var realDateTime = dateTime ?? DateTime.UtcNow;
}

......但这并不总是合适的。

结论:

  • 我非常怀疑这是否会成为 C# 的一部分
  • 对于 string.Empty 来说,无论如何它都是毫无意义的
  • 对于其他确实总是具有相同值的值,这真的可能很痛苦

From the original question:

I thought that we would use it to be sure that we have a system-independent means of referring to the empty string.

In what way can the empty string vary from system to system? It's always a string with no characters! I'd be really scared if I ever found an implementation where string.Empty == "" returned false :) This is not the same as something like Environment.NewLine.

From Counter Terrorist's bounty post:

I want String.Empty can be used as a default parameter in the next C# release. :D

Well that's certainly not going to happen.

While I would personally have liked a very different defaulting mechanism too, the way optional parameters work has been in .NET since the start - and it always means embedding a constant into the metadata, so that the calling code can copy that constant into the call site if no corresponding argument is provided.

With string.Empty it's really pointless - using "" will do what you want; is it that painful to use the string literal? (I use the literal everywhere - I never use string.Empty - but that's a different argument.)

That's what surprises me about this question - the complaint revolves around something which doesn't actually cause a real problem. It's for more important in cases where you want the default to be computed at execution time because it might actually vary. For example, I could imagine cases where you want to be able to call a method with a DateTime parameter and have it default to "the current time". At the moment, the only vaguely elegant workaround I know for that is:

public void RecordTime(string message, DateTime? dateTime = null)
{
    var realDateTime = dateTime ?? DateTime.UtcNow;
}

... but that's not always appropriate.

In conclusion:

  • I very much doubt that this will ever be part of C#
  • For string.Empty it's pointless anyway
  • For other values which really don't always have the same value, it really can be a pain
奢华的一滴泪 2024-09-06 05:31:55

我从不使用 string.Empty,我看不出它的意义。也许它对于那些真正刚接触编程的人来说更容易,但我怀疑它是否有用。

I never use string.Empty, I can't see the point of it. Maybe it makes it easier for people that are really new to programming, but I doubt it's useful even for that.

混吃等死 2024-09-06 05:31:55

我认为 string.Empty 背后的想法是它增强了可读性。它不像换行符那样在不同平台上的表示方式有任何差异。遗憾的是它不能在默认参数中使用。但是,如果您在 Windows 和 Linux 上的 Mono 之类的东西之间移植,它不会造成任何问题。

I think the idea behind string.Empty is it enhances readability. It is not like newline where there is any difference between how it is represented on different platforms. It's ashame it can't be used in a default parameter. However, it will not cause any issues if you port between Windows and something like Mono on Linux.

£烟消云散 2024-09-06 05:31:55

仅供参考,看起来传递给属性构造函数的值也受到了相同的约束 - 它们必须是常量。由于 string.empty 被定义为 :

public static readonly string Empty

而不是实际的常量,因此无法使用它。

As a FYI, it looks like the same constraint is imposed on values passed to attribute constructors - they must be constant. Since string.empty is defined as :

public static readonly string Empty

rather than an actual constant, it cannot be used.

极致的悲 2024-09-06 05:31:55

我使用 string.Empty 纯粹是为了可读性。

如果其他人稍后需要阅读/更改我的代码,他们知道我的意思是检查或将某些内容设置为空字符串。仅使用 "" 有时会导致错误和混乱,因为我可能只是忘记将我想要的字符串放在那里。

例如:

if(someString == string.Empty)
{

}

vs

if(someString == "")
{

}

第一个 if 语句对我来说似乎更加深思熟虑和可读。因为这只是一个偏好,所以我真的没有看到必须使用 "" 而不是 string.Empty 的火车粉碎。

I use string.Empty purely for readability.

If someone else needs to read/change my code later they know that I meant to check for or set something to an empty string. Using just "" can sometimes cause bugs and confusion because I may have just forgot to put the string that I wanted in there.

For example:

if(someString == string.Empty)
{

}

vs

if(someString == "")
{

}

The first if statement just seems so much more deliberate and readable to me. Because this is just a preference though, I really do not see the train-smash in having to use "" instead of string.Empty.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文