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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

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

其他回答

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

我没有什么区别。最后一个是打字最快的:)

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

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

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

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

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

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

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