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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

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

其他回答

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

没有人提到在VisualStudio中字符串的颜色编码与字符串不同。这对可读性很重要。此外,小写通常用于变量和类型,不是什么大问题,而是字符串。Empty是常量,而不是变量或类型。

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.

使用您和您的团队认为最易读的内容。

其他答案表明,每次使用""都会创建一个新的字符串。这是不正确的-由于字符串实习,它将在每个程序集或每个AppDomain创建一次(或可能在整个过程中创建一次-在这方面不确定)。这种差异可以忽略不计——非常非常微不足道。

然而,你觉得哪个更有可读性是另一回事。这是主观的,因人而异——所以我建议你找出你的团队中大多数人喜欢什么,然后保持一致。我个人觉得“”更容易读。

“”和“”很容易被误认为彼此的论点并不能真正让我接受。除非你使用的是比例字体(我从未与任何使用比例字体的开发人员合作过),否则很容易看出区别。

我使用“”,因为它将在我的代码中被明显地涂成黄色……字符串。在我的Visual Studio Code主题中,空是白色的。我相信这对我来说最重要。