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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

以上任何一种。

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

其他回答

字符串。空和字符串。空的是等价的。String是BCL类名;字符串是它的c#别名(或快捷方式,如果你愿意)。与Int32和int相同。更多示例请参见文档。

至于“”,我不太确定。

就我个人而言,我总是使用string.Empty。

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

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

http://blogs.msdn.com/b/brada/archive/2003/04/22/49997.aspx:

As David implies, there difference between String.Empty and "" are pretty small, but there is a difference. "" actually creates an object, it will likely be pulled out of the string intern pool, but still... while String.Empty creates no object... so if you are really looking for ultimately in memory efficiency, I suggest String.Empty. However, you should keep in mind the difference is so trival you will like never see it in your code... As for System.String.Empty or string.Empty or String.Empty... my care level is low ;-)

前两种我都可以接受。我将避免使用最后一种方法,因为在引号之间加空格很容易引入错误。这种特殊的缺陷很难通过观察发现。假设没有错别字,所有这些在语义上都是等价的。

(编辑)

另外,为了保持一致性,你可能总是想使用string或string,但这只是我的想法。

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