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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

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

如果你使用字符串,我发现编译器的行为有所不同。空引号或双引号。如果你不使用用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是string的别名,但在赋值中看到它们会让人感觉不舒服。

我认为第二个是“合适的”,但老实说,我不认为这有什么关系。编译器应该足够聪明,可以将其中任何一个编译为完全相同的字节码。我用“myself”。

虽然差别非常非常小,但差别仍然存在。

""在String时创建一个对象。空则不然。但是这个对象只创建一次,如果代码中有另一个"",就会从字符串池中引用它。 String和String是一样的,但是我建议使用String。空(以及字符串。格式字符串。因为点表示法表示的是类,而不是操作符,而且类以大写字母开头符合c#编码标准。

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.)

以上任何一种。

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