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

其他回答

一个不同之处在于,如果使用切换大小写语法,就不能编写大小写字符串。空:因为它不是一个常数。您将得到一个编译错误:期望一个常量值

更多信息请看这个链接: string-empty-versus-empty-quotes

我个人更喜欢“”,除非有很好的理由去做更复杂的事情。

没有人提到在VisualStudio中字符串的颜色编码与字符串不同。这对可读性很重要。此外,小写通常用于变量和类型,不是什么大问题,而是字符串。Empty是常量,而不是变量或类型。

如果你想恶作剧某人,在他们的代码中加入“‍”。这不是空字符串,它是“\u200D”。你不能用string.Empty欺骗别人。

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