为什么字符串不比较引用?

发布于 2024-10-20 11:09:05 字数 69 浏览 1 评论 0原文

我知道这是特殊情况,但为什么字符串之间的 == 在它们的值相等时返回,而不是在它们的引用相等时返回。这与重载运算符有关系吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

你列表最软的妹 2024-10-27 11:09:05

实际上,== 运算符在 String 中重载,以执行值相等而不是引用相等。这个想法是让字符串对程序员更加友好,并避免使用引用相等来比较它们时出现的错误(在 Java 中并不少见,尤其是对于初学者)。

老实说,到目前为止,我从来不需要通过引用来比较字符串。如果您需要这样做,可以使用 object.ReferenceEquals()

The == operator is overloaded in String 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().

凹づ凸ル 2024-10-27 11:09:05

因为字符串是不可变的,并且运行时可能选择将任意两个具有相同内容的字符串放在同一个引用中。所以引用比较字符串实际上没有任何意义。

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.

城歌 2024-10-27 11:09:05

在字符串上, == 通过 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 类的相等运算符重载:

public static bool operator ==(string a, string b)
{
    return Equals(a, b);
}

Yes. From .NET Reflector here is the equality operator overloading of String class:

public static bool operator ==(string a, string b)
{
    return Equals(a, b);
}
§普罗旺斯的薰衣草 2024-10-27 11:09:05

相等运算符(==!=)被定义为比较字符串对象的,而不是引用。

在任何情况下我都必须比较参考文献,但如果你想这样做,那么你可以使用:

object.ReferenceEquals().

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:

object.ReferenceEquals().
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文