Object.ReferenceEquals returns incorrect results (in Silverlight 3 at least)

☆樱花仙子☆ 提交于 2019-12-24 07:28:25

问题


I just discovered a very strange behaviour. I have a class with a string property. In the setter of this property I compare the old value with the new value first and only change property if the values differ:

        set
        {
            if ((object.ReferenceEquals(this.Identifier, value) != true))
            {
                this.Identifier = value;
                this.RaisePropertyChanged("Identifier");
            }
        }

But this ReferenceEquals almost always returns false! Even if I call object.ReferenceEquals("test", "test") in Quick Watch I get false.

How is this possible?


回答1:


That's because strings are immutable in C#:

The contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this.

Since you can't modify an existing string reference, there's no benefit in reusing them. The value passed to your property setter will always be a new string reference, except maybe if you do this.Identifier = this.Identifier;.

I'll try to clarify with an example:

string s = "Hello, ";  // s contains a new string reference.
s += "world!";         // s now contains another string reference.


来源:https://stackoverflow.com/questions/4106021/object-referenceequals-returns-incorrect-results-in-silverlight-3-at-least

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!