2010-11-05 15 views
1

我剛發現一個非常奇怪的行爲。我有一個字符串屬性的類。在此setter方法我首先比較舊值與新值,只有當值不同改變屬性:Object.ReferenceEquals返回不正確的結果(至少在Silverlight 3中)

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

但這幾乎的ReferenceEquals始終返回false!即使我在快速查看中調用object.ReferenceEquals(「test」,「test」)我也會得到錯誤信息。

這怎麼可能?

回答

0

這是因爲strings are immutable在C#:

一個String對象的內容後,創建對象 不能 改變,雖然語法使得 出現,如果你能做到這一點。

由於您無法修改現有的字符串引用,因此重用它們沒有任何好處。傳遞給你的屬性setter的值將永遠是一個新的字符串引用,除非你做this.Identifier = this.Identifier;

我會嘗試用一個例子來闡明:

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