问题描述
根据,,
和的String.Empty
非常略有不同,在,
创建一个对象,而的String.Empty
没有。这个问题的答案对这个问题的多数选票。
According to this answer, ""
and string.Empty
are very slightly different, in that ""
creates an object, whereas string.Empty
does not. That answer has the most votes on that question.
不过,说,没有什么区别。这是一个更近的回答也是如此。
However, this answer says that there is no difference. It's a more recent answer as well.
因此,这是在2010年这是真的吗?做的String.Empty
和,
不同不惜一切,甚至略带?
So this was in 2010. Is this really the case? Do string.Empty
and ""
differ at all, even slightly?
编辑:这个问题,就是要更新到链接的问题,因为我发现它令人困惑,没有现代化的答案已经提交,尽管对此事的一些争论
This question is meant to be an update to the linked questions, as I found it confusing that no modern answer had been presented, despite some debate on the matter.
推荐答案
语言规范(C#4.0)是关于这个问题实际上是沉默。
The language specification (C# 4.0) is actually silent on the subject.
据通过C#CLR,这完全取决于CLR,而不是C#编译器。从P A的相关报价。 341:
According to CLR via C#, it depends entirely on the CLR and not on the C# compiler. A relevant quote from p. 341:
即使一个装配有这个属性/标志[CompilationRelaxations.NoStringInterning]规定,CLR可以选择实习生字符串,但你不应该指望这个。其实,你真的不应该编写依赖于被拘留,除非你写的代码,明确要求字符串的实习生方法自己的字符串代码。
因此,使用,
可能会或可能不会创建一个新的字符串对象。这取决于所使用的CLR(版本)。也有编译器折叠常数,在这种情况下,的可能性
将花费每编译单元,而不是每发生1对象。
So using ""
may or may not create an new string object. That depends on the CLR (version) being used. And there's also the possibility that the compiler folds constants, in which case ""
would cost 1 object per compilation unit, not per occurrence.
这一切都不对内存使用或速度的任何相关的影响,但明确的指导方针应该是,既的ReferenceEquals(S1,)
和的ReferenceEquals(S1,的String.Empty)
应尽量避免。
None of this has any relevant impact on memory use or speed, but the clear guideline should be that both ReferenceEquals(s1, "")
and ReferenceEquals(s1, String.Empty)
should be avoided.
当然,的Object.Equals(S1,S2)
和 S1 S2 = =
总是在字符串正常工作。
And of course Object.Equals(s1, s2)
and s1 == s2
always work fine on strings.
这篇关于主场迎战的String.Empty"" - 现在会有改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!