为什么字符串不比较引用?
我知道这是特殊情况,但为什么字符串之间的 == 在它们的值相等时返回,而不是在它们的引用相等时返回。这与重载运算符有关系吗?
I know it is special case but why == between strings returns if their value equals and not when their reference equals. Does it have something to do with overlloading operators?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
实际上,
==
运算符在String
中重载,以执行值相等而不是引用相等。这个想法是让字符串对程序员更加友好,并避免使用引用相等来比较它们时出现的错误(在 Java 中并不少见,尤其是对于初学者)。老实说,到目前为止,我从来不需要通过引用来比较字符串。如果您需要这样做,可以使用
object.ReferenceEquals()
。The
==
operator is overloaded inString
to perform value equality instead of reference equality, indeed. The idea is to make strings more friendly to the programmer and to avoid errors that arise when using reference equality to compare them (not too uncommon in Java, especially for beginners).So far I have never needed to compare strings by reference, to be honest. If you need to do it you can use
object.ReferenceEquals()
.因为字符串是不可变的,并且运行时可能选择将任意两个具有相同内容的字符串放在同一个引用中。所以引用比较字符串实际上没有任何意义。
Because strings are immutable and the runtime may choose to put any two strings with the same content together into the same reference. So reference-comparing strings doesn't really make any sense.
在字符串上, == 通过 value
"尽管字符串是引用类型,但定义了相等运算符(== 和 !=)来比较字符串对象的值,而不是引用(7.9.7 字符串相等运算符)。字符串相等更直观。”
简而言之,字符串上的 == 按值比较字符串,而不是按引用比较字符串,因为 C# 规范规定它应该这样做。
on a string, == compares by value
"Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references (7.9.7 String equality operators). This makes testing for string equality more intuitive."
In short, == on strings compares the strings by value, not by reference, because the C# specification says it should.
是的。来自 .NET Reflector,这里是
String
类的相等运算符重载:Yes. From .NET Reflector here is the equality operator overloading of
String
class:相等运算符(
==
和!=
)被定义为比较字符串对象的值,而不是引用。在任何情况下我都必须比较参考文献,但如果你想这样做,那么你可以使用:
The equality operators (
==
and!=
) are defined to compare the values of string objects, not references.There was not any situation in which I had to compare the references but if you want to do so then you can use: