在c#中,我想用空字符串初始化一个字符串值。

我该怎么做呢? 什么是正确的方法,为什么?

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

The empty string is like empty set just a name that everybody uses to call "". Also in formal languages strings created from an alphabet that have zero length are called the empty string. Both set and string have a special symbol for it. Empty string: ε and empty set: ∅. If you want to talk about this zero length string you will call it the empty string so everybody knows exactly what you are referring to. Now in case you name it the empty string why not use string.Empty in code, its shows the intention is explicit. Downside is that it’s not a constant and therefore not available everywhere, like in attributes. (It's not a constant for some technical reasons, see the reference source.)

其他回答

I strongly prefer String.Empty, aside from the other reasons to ensure you know what it is and that you have not accidentally removed the contents, but primarily for internationalization. If I see a string in quotes then I always have to wonder whether that is new code and it should be put into a string table. So every time code gets changed/reviewed you need to look for "something in quotes" and yes you can filter out the empty strings but I tell people it is good practice to never put strings in quotes unless you know it won't get localized.

以上任何一种。

还有很多很多更好的事情可以指手画脚。比如什么颜色的树皮最适合一棵树,我认为是模糊的棕色和淡淡的苔藓。

这个话题已经很老很长了,所以如果在其他地方提到过这种行为,请原谅。(并指出我的答案,包括这个)

如果你使用字符串,我发现编译器的行为有所不同。空引号或双引号。如果你不使用用string初始化的string变量,区别就会显现出来。为空或带双引号。

在初始化字符串的情况下。空,然后编译器警告

CS0219 - The variable 'x' is assigned but its value is never used

永远不会触发,而在使用双引号初始化的情况下,您将获得预期的消息。

这种行为在Connect文章中有解释,链接:https://connect.microsoft.com/VisualStudio/feedback/details/799810/c-warning-cs0219-not-reported-when-assign-non-constant-value

基本上,如果我做对了,他们希望允许程序员用函数的返回值设置一个变量用于调试目的,而不用警告消息来打扰他,因此他们只在常量赋值和字符串的情况下限制警告。空不是常数,而是场。

几年后 微软已经关闭了https://connect .microsoft.com网站,因此没有更多可用的讨论。然而,这篇文章https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0219有一个有趣的评论,似乎证实了前面的原因:

只有当变量值为a时,编译器才会生成此警告 编译时常量。指定一个非常量表达式或方法 结果的局部变量,使观察这些更容易 调试器中的表达式。它还使结果可达, 在该变量可达时防止垃圾收集。

几乎每个开发者都知道“”是什么意思。我个人就遇到过String。第一次是空的,必须花一些时间搜索谷歌来确定它们是否真的是完全相同的东西。

我喜欢用绳子。空字符串。空的,因为你可以使用它而不需要包含一个using System;在你的档案里。

至于在字符串上选择“”。空,这是个人喜好,应该由你的团队决定。