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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

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.)

其他回答

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

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

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

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

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

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.

如果你想恶作剧某人,在他们的代码中加入“‍”。这不是空字符串,它是“\u200D”。你不能用string.Empty欺骗别人。

我亲眼目睹了两次“导致(小)问题”。一次是由于一个刚接触基于团队编程的初级开发人员的错误,另一次是一个简单的拼写错误,但事实是使用了字符串。空本来可以避免这两个问题。

是的,这在很大程度上是一种判断,但是当一种语言提供了多种方法来做事情时,我倾向于使用具有最多编译器监督和最强编译时强制的语言。那不是“”。这一切都是为了表达具体的意图。

如果你输入字符串。EMpty或string。空,编译器让你知道你做错了。立即。它根本不会编译。作为一个开发人员,你引用的是编译器(或其他开发人员)不能以任何方式误解的特定意图,当你做错了,你不能创建一个bug。

如果你输入“”当你想要“”时,反之亦然,编译器会很高兴地执行你让它做的事情。其他开发人员可能无法收集到您的特定意图。Bug。

早在字符串出现之前。Empty是我使用的标准库,它定义了EMPTY_STRING常量。我们仍然在case语句中使用这个常量。不允许为空。

只要可能,让编译器为你工作,并消除人为错误的可能性,无论多么小。在我看来,这比“可读性”更重要。

专用性和编译时强制。这是晚餐要吃的。