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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

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

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

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

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

其他回答

我喜欢用绳子。空字符串。空的,因为你可以使用它而不需要包含一个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.)

我本来不想插嘴的,但我发现这里有一些错误的信息。

我个人更喜欢字符串。这是个人喜好,我会根据具体情况服从与我合作的任何团队的意愿。

正如其他人所提到的,字符串和字符串之间根本没有区别。Empty和String.Empty。

此外,这是一个鲜为人知的事实,使用“”是完全可以接受的。在其他环境中,“”的每个实例都将创建一个对象。然而,. net会实习它的字符串,因此未来的实例将从实习池中提取相同的不可变字符串,任何性能损失都可以忽略不计。来源:布拉德·艾布拉姆斯。

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

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