1
可以說我有一個類定義如下所示。現在讓我說我進一步修改這個類來正確實現NotifyPropertyChanged並添加到我綁定到WPF網格的集合 。如果代碼執行那些更改其中一個實例的Name或Description屬性,其他人是否也會更新? WPF/XAML綁定是否將這些對象視爲同一個對象,還是將對象視爲不同對象,只更新已更改的對象的屬性?綁定和Overiding模型的相等和哈希碼
class Security
{
public string Ticker { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public override bool Equals(object obj)
{
if (obj == null) return false;
if (this.GetType() != obj.GetType()) return false;
Security security = (Security)obj;
//reference check
//if (!Object.Equals(Ticker, security.Ticker)) return false;
//value member check
if (!Ticker.Equals(security.Ticker)) return false;
return true;
}
public static bool operator ==(Security sec1, Security sec2)
{
if (System.Object.ReferenceEquals(sec1, sec2)) return true;
if (((object)sec1 == null) || ((object)sec2 == null)) return false;
// Return true if the fields match:
return sec1.Ticker == sec2.Ticker;
}
public static bool operator !=(Security sec1, Security sec2)
{
return !(sec1 == sec2);
}
public override int GetHashCode()
{
unchecked
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + Ticker.GetHashCode();
hash = hash * 23 + Ticker.GetHashCode();
hash = hash * 23 + Ticker.GetHashCode();
return hash;
}
}
}
謝謝..這是我想我知道的。我可能沒有清楚地解釋這個問題。它有點難以解釋...可以說我重寫equals和gethashcode這樣的等式不是基於引用,而是一個屬性的內容。如果我的類的兩個實例綁定到兩個文本框,但是根據新定義的相等性,它們實際上是相等的。將更新一個導致另一個也會被解壓縮? – mike01010
@ mike01010我不這麼認爲。我不知道Binding是如何實現的,但我的猜測是它們被鍵入,並且引發PropertyChanged會導致查找表刷新引用 - 該引用僅指向您的類的一個實例。 –