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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

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

至于“”,我不太确定。

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

其他回答

我更喜欢字符串而不是字符串。选择字符串。空而不是“”是选择一个并坚持下去的问题。使用字符串的优点。空是很明显你的意思,你不会不小心复制了不可打印的字符,如“\x003”在你的“”。

我用的是第三个,但在其他两个中,第一个似乎没那么奇怪。 string是string的别名,但在赋值中看到它们会让人感觉不舒服。

我喜欢用绳子。空字符串。空的,因为你可以使用它而不需要包含一个using System;在你的档案里。

至于在字符串上选择“”。空,这是个人喜好,应该由你的团队决定。

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是BCL类名;字符串是它的c#别名(或快捷方式,如果你愿意)。与Int32和int相同。更多示例请参见文档。

至于“”,我不太确定。

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