簡體   English   中英

重寫Equals和GetHashCode不一定會覆蓋相等重載運算符

[英]Overriding Equals and GetHashCode doesn't necessarily override equality overloading operator

我有以下代碼:

public enum ClassType
{
    I,
    II,

}

public enum LocationType
{
    A,
    B
}
public class Person
{
    public LocationType LocType
    { get; set; }
    public ClassType ClaType
    { get; set; }


    public override bool Equals(object obj)
    {
        Person obPer = obj as Person;
        if (obPer == null)
            return false;
        if (LocType != obPer.LocType)
            return false;
        if (ClaType != obPer.ClaType)
            return false;
        return true;

    }

    public override int GetHashCode()
    {
        return LocType.GetHashCode()^ClaType.GetHashCode();
    }

}

  static void Main(string[] args)
    {

        var p1 = new Person()
        {
            ClaType = ClassType.I,
            LocType = LocationType.A
        };


        var p2 = new Person()
        {
            ClaType = ClassType.I,
            LocType = LocationType.A
        };

        bool isEqual1 = p1.Equals(p2);  //true
        bool getHashCodeNum = p1.GetHashCode() == p2.GetHashCode();  //true
        bool isEqual2 = p1 == p2;  //false
    }

我發現isEqual1=truegetHashCodeNum=true ,但isEqual2=false

我希望由於我已經重寫了EqualsGetHashCode ,所以operator ==應該自動遵循Equals的行為,但事實並非如此。 任何原因?

==運營商 你可以在兩個Person 重載 ==運算符,如下所示:

public class Person {

    //..

    public static bool operator == (Person a, Person b)
    {
        if (Object.ReferenceEquals(a,null) && Object.ReferenceEquals(b,null))
            return true;
        if (Object.ReferenceEquals(a,null) || Object.ReferenceEquals(a,null))
            return false;
        return a.LocType == b.LocType && a.ClaType != b.ClaType;
    }

    public static bool operator != (Person a, Person b)
    {
       return ! (a == b);
    }

}

==!=是對:你需要實現!=如果你實現==反之亦然,否則你得到錯誤:

錯誤CS0216:運算符Person.operator ==(Person, Person)需要匹配的運算符!=也要定義

現在當你比較兩個Person它應該有效。 但是請注意,不要覆蓋相等運算符, 否則 會使它們超載 所以編譯器會選擇==實現(這不是在運行時通過動態綁定完成的)。 結果是:

bool isEqual2 = p1 == p2;  //true
bool isEqual3 = (object) p1 == p2;  //false
bool isEqual4 = p1 == (object) p2;  //false
bool isEqual5 = (object) p1 == (object) p2;  //false

默認情況下, == over兩個object引用相等,所以只有當這兩個參數是Person ,我們檢查這兩個對象是否相同

因此,如果要使用動態綁定檢查相等性,則最好使用Equals(..)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM