在c#中,我想用空字符串初始化一个字符串值。
我该怎么做呢? 什么是正确的方法,为什么?
string willi = string.Empty;
or
string willi = String.Empty;
or
string willi = "";
还是别的什么?
在c#中,我想用空字符串初始化一个字符串值。
我该怎么做呢? 什么是正确的方法,为什么?
string willi = string.Empty;
or
string willi = String.Empty;
or
string willi = "";
还是别的什么?
当前回答
我亲眼目睹了两次“导致(小)问题”。一次是由于一个刚接触基于团队编程的初级开发人员的错误,另一次是一个简单的拼写错误,但事实是使用了字符串。空本来可以避免这两个问题。
是的,这在很大程度上是一种判断,但是当一种语言提供了多种方法来做事情时,我倾向于使用具有最多编译器监督和最强编译时强制的语言。那不是“”。这一切都是为了表达具体的意图。
如果你输入字符串。EMpty或string。空,编译器让你知道你做错了。立即。它根本不会编译。作为一个开发人员,你引用的是编译器(或其他开发人员)不能以任何方式误解的特定意图,当你做错了,你不能创建一个bug。
如果你输入“”当你想要“”时,反之亦然,编译器会很高兴地执行你让它做的事情。其他开发人员可能无法收集到您的特定意图。Bug。
早在字符串出现之前。Empty是我使用的标准库,它定义了EMPTY_STRING常量。我们仍然在case语句中使用这个常量。不允许为空。
只要可能,让编译器为你工作,并消除人为错误的可能性,无论多么小。在我看来,这比“可读性”更重要。
专用性和编译时强制。这是晚餐要吃的。
其他回答
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.
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.)
我使用“”,因为它将在我的代码中被明显地涂成黄色……字符串。在我的Visual Studio Code主题中,空是白色的。我相信这对我来说最重要。
最好的代码是没有代码:
编码的基本性质是,作为程序员,我们的任务是认识到我们所做的每一个决定都是一种权衡。从简洁开始。根据测试的需要增加其他维度。
因此,代码越少越好:更喜欢“”而不是字符串。Empty或String.Empty。这两篇文章的篇幅长了六倍,但没有额外的好处——当然也没有额外的清晰度,因为它们表达的信息完全相同。
字符串。空和字符串。空的是等价的。String是BCL类名;字符串是它的c#别名(或快捷方式,如果你愿意)。与Int32和int相同。更多示例请参见文档。
至于“”,我不太确定。
就我个人而言,我总是使用string.Empty。