我對C#中的Equals和GetHashCode的默認行爲有點困惑。 說我有兩個班,從另外一個推導:覆蓋Equals和GetHashCode - 派生類中的默認實現
public abstract class Question
{
public string QuestionText
{
get;
set;
}
public override bool Equals(object obj)
{
if (obj is Question)
{
Question q = (Question)obj;
return this.QuestionText.Equals(q.QuestionText);
}
else
{
return false;
}
}
public override int GetHashCode()
{
int hash = 13;
hash = (hash * 7) + this.QuestionText.GetHashCode();
return hash;
}
}
public class QuestionTrueFalse : Question
{
public bool CorrectAnswer
{
get;
set;
}
public override bool Equals(object obj)
{
return base.Equals(q);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
派生類不影響一個項目是否等於另一個,我還是希望是簡單地於QuestionText財產爲基礎。
我是否需要覆蓋Equals和GetHashCode來引用基礎實現,正如我在這裏所做的,或者是默認行爲?
你爲什麼不只是寫'公共覆蓋INT的GetHashCode(){返回91 +本.QuestionText.GetHashCode(); }'? – phoog