重构:替换为 Constant String.Empty
我有以下代码行
Dim a As String = ""
,重构建议将 ""
替换为 String.Empty
这是一种重构,但为什么呢?由于我是我未来声明的新手,我应该更好地使用 String.Empty
吗?
I have the following line of code
Dim a As String = ""
and the Refactor suggests replacing the ""
with String.Empty
It is a kind of Reafactoring but why? Since i am a newbie in the future declarations of mine should i better use the String.Empty
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这实际上主要是一个偏好问题。就我个人而言,我发现 String.Empty 更清楚地显示了程序员的意图(例如,他没有意外地放置空字符串而不是空格)......这可能就是“Refactor”建议它的原因。但除此之外,它们是完全相同的。按照您认为合适的方式进行此操作。
It's mostly a matter of preference really. Personally, I find String.Empty more clearly shows the programmer's intent (for example, that he didn't accidentally put an empty string instead of a space)... that's probably why "Refactor" suggests it. But other than that, they're exactly the same thing. Do as you see fit on this one.
String.Empty 字段的值为零- 长度字符串,“”。
在应用程序代码中,此字段最常用于将字符串变量初始化为空字符串的赋值。要测试字符串的值是否为 null 或 String.Empty,请使用 IsNullOrEmpty 方法。
The value of the String.Empty field is the zero-length string, "".
In application code, this field is most commonly used in assignments to initialize a string variable to an empty string. To test whether the value of a string is either null or String.Empty, use the IsNullOrEmpty method.
这很大程度上取决于个人喜好。我更喜欢尽可能使用常量,特别是如果我正在使用的框架已经提供了常量。我不会竭尽全力消除代码中所有“”的使用。 (特别是因为编译器将折叠字符串文字的所有重复项,并仅在运行时保留其中之一。)
It's pretty much a matter of personal preference. I prefer using constants whenever possible, especially so if they are already provided by the framework I'm using. I wouldn't go out of my way to eliminate every use of "" in the code. (Especially since the compiler will fold all repetitions of a string literal and keep only one of them for runtime.)
"" 可能会创建一个新的 String 对象,而 String.Empty 则引用预定义的(现有的)对象。这是一个小问题,但这就是重构工具的作用:找到各种问题,包括小问题。
"" potentially creates a new String object, while String.Empty refers to a predefined (existing) object. It's a minor nitpick, but that's what refatoring tools do: find all kinds of issues, inluding minor nitpicks.
我总是采取相反的做法,将字符串设置为
null
。实际上在某些情况下,您想要使用“”来表示您已经构建了一个字符串但没有内容。通常你的意思是你没有构建字符串。这就是为什么我更喜欢null
构造。I always go the opposite and set the string to
null
. There are really a few situations where want you want to mean with "" is that you have a string built but with no content. Usually what you mean is that you have the string unbuilt. That's why I prefer thenull
construct.