简体   繁体   English

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

[英]Why strings does not compare references?

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? 它与重载运算符有关吗?

The == operator is overloaded in String to perform value equality instead of reference equality, indeed. 实际上, ==运算符在String重载以执行值相等而不是引用相等。 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). 我们的想法是让字符串对程序员更友好,并避免在使用引用相等性来比较它们时出现的错误(在Java中并不常见,特别是对于初学者而言)。

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() . 如果需要,可以使用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. 所以参考比较字符串并没有任何意义。

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." “尽管string是一个引用类型,但是相等运算符(==和!=)被定义为比较字符串对象的值,而不是引用(7.9.7字符串相等运算符)。这使得对字符串相等性的测试更加直观。”

In short, == on strings compares the strings by value, not by reference, because the C# specification says it should. 简而言之,== on strings比较字符串的值,而不是引用,因为C#规范说它应该。

Yes. 是。 From .NET Reflector here is the equality operator overloading of String class: 从.NET Reflector这里是String类的相等运算符重载:

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

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().

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM