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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

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

至于“”,我不太确定。

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

其他回答

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

至于“”,我不太确定。

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

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

(编辑)

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

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

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.

以上任何一种。

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