在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 = "";
还是别的什么?
当前回答
我喜欢用绳子。空字符串。空的,因为你可以使用它而不需要包含一个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。第一次是空的,必须花一些时间搜索谷歌来确定它们是否真的是完全相同的东西。
没有人提到在VisualStudio中字符串的颜色编码与字符串不同。这对可读性很重要。此外,小写通常用于变量和类型,不是什么大问题,而是字符串。Empty是常量,而不是变量或类型。
我亲眼目睹了两次“导致(小)问题”。一次是由于一个刚接触基于团队编程的初级开发人员的错误,另一次是一个简单的拼写错误,但事实是使用了字符串。空本来可以避免这两个问题。
是的,这在很大程度上是一种判断,但是当一种语言提供了多种方法来做事情时,我倾向于使用具有最多编译器监督和最强编译时强制的语言。那不是“”。这一切都是为了表达具体的意图。
如果你输入字符串。EMpty或string。空,编译器让你知道你做错了。立即。它根本不会编译。作为一个开发人员,你引用的是编译器(或其他开发人员)不能以任何方式误解的特定意图,当你做错了,你不能创建一个bug。
如果你输入“”当你想要“”时,反之亦然,编译器会很高兴地执行你让它做的事情。其他开发人员可能无法收集到您的特定意图。Bug。
早在字符串出现之前。Empty是我使用的标准库,它定义了EMPTY_STRING常量。我们仍然在case语句中使用这个常量。不允许为空。
只要可能,让编译器为你工作,并消除人为错误的可能性,无论多么小。在我看来,这比“可读性”更重要。
专用性和编译时强制。这是晚餐要吃的。
我只是在看一些代码,然后这个问题突然出现在我的脑海里,这个问题是我以前读过的。这当然是可读性的问题。
考虑下面的c#代码…
(customer == null) ? "" : customer.Name
vs
(customer == null) ? string.empty : customer.Name
我个人认为后者不那么模棱两可,也更容易阅读。
正如其他人指出的那样,实际的差异可以忽略不计。