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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

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-empty-versus-empty-quotes

编译器应该让它们在长期运行时都是一样的。选择一个标准,这样你的代码就容易阅读,并坚持下去。

我更喜欢字符串而不是字符串。选择字符串。空而不是“”是选择一个并坚持下去的问题。使用字符串的优点。空是很明显你的意思,你不会不小心复制了不可打印的字符,如“\x003”在你的“”。

我本来不想插嘴的,但我发现这里有一些错误的信息。

我个人更喜欢字符串。这是个人喜好,我会根据具体情况服从与我合作的任何团队的意愿。

正如其他人所提到的,字符串和字符串之间根本没有区别。Empty和String.Empty。

此外,这是一个鲜为人知的事实,使用“”是完全可以接受的。在其他环境中,“”的每个实例都将创建一个对象。然而,. net会实习它的字符串,因此未来的实例将从实习池中提取相同的不可变字符串,任何性能损失都可以忽略不计。来源:布拉德·艾布拉姆斯。

这可能是一个有争议的评论,但是,总的来说,我发现当我与微软保持一致时,我的生活更容易。我们不可能知道他们做事的全部深层原因(我想有时是非常严格的,有时是笨拙的)。

他们在自动生成的文件(如Assembly文件)中使用“”,所以这就是我所做的。事实上,当我尝试用字符串替换任何下面的“”。空,Visual Studio崩溃在我身上。这可能有一个合乎逻辑的解释,但以我有限的知识,如果我只是做他们做的事情,大多数时候,事情都会解决。(反:我知道一些自动生成的文件也使用字符串。空的,这有点打破我的观点。:))

<Assembly: System.Reflection.AssemblyCulture("")>
<Assembly: System.Reflection.AssemblyDescription("")>
<Assembly: System.Reflection.AssemblyFileVersion("1.0.0.0")>
<Assembly: System.Reflection.AssemblyKeyFile("")>
<Assembly: System.Reflection.AssemblyProduct("")>
<Assembly: System.Reflection.AssemblyTitle("")>