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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

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

其他回答

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

以上任何一种。

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

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.

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

这完全是一个代码风格的偏好,就像。net如何处理字符串一样。然而,以下是我的观点:

我总是使用BCL类型名称访问静态方法,属性和字段:字符串。Empty或Int32.TryParse(…)或Double。ε

我总是在声明新实例时使用c#关键字:或者string foo = "bar";

我很少使用未声明的字符串字面量,因为我喜欢能够扫描代码,将它们组合成可重用的命名常量。编译器无论如何都会用字面量替换常量,所以这是一种避免神奇的字符串/数字,并通过名称赋予它们更多含义的方法。另外,更改值更容易。