Equal與==都可以被重寫进鸠,但要把握的原則是:
重寫Equal來表示值相等蛮位,而不重寫==繼續(xù)讓其表示引用相同
<pre>
class Person
{
public Person(int id)
{
ID = id;
}
public string ID{get; private set;}
<font color=blue>
public override bool Equals(object obj)
{
Person p = obj as Person;
if(p == null)
return false;
return ID == p.ID;
}
</font>
<font color=red>
// 這里要注意诵叁,一定要重寫GetHashCode()方法
// 否則會(huì)出現(xiàn)當(dāng)值相等的兩個(gè)Person做為key在Dictionary中時(shí)价淌,會(huì)認(rèn)為是兩個(gè)不同的key
pubic override int GetHashCode()
{
return ID.GetHashCode();
}
</font>
}
</pre>