2016-04-23 57 views
1

我有一個名爲City的自定義類,這個類有一個Equals方法。將數組與指定變量進行比較時,SequenceEqual方法可以很好地工作。比較包含格式爲new City()的元素的兩個數組時,會出現該問題。結果是錯誤的。如何在C#中檢查自定義類數組的相等性?

市類:

interface IGene : IEquatable<IGene> 
{ 
    string Name { get; set; } 
    int Index { get; set; } 
} 
class City : IGene 
{ 
    string name; 
    int index; 
    public City(string name, int index) 
    { 
     this.name = name; 
     this.index = index; 
    } 
    public string Name 
    { 
     get 
     { 
      return name; 
     } 
     set 
     { 
      name = value; 
     } 
    } 

    public int Index 
    { 
     get 
     { 
      return index; 
     } 
     set 
     { 
      index = value; 
     } 
    } 

    public bool Equals(IGene other) 
    { 
     if (other == null && this == null) 
      return true; 
     if((other is City)) 
     { 
      City c = other as City; 
      return c.Name == this.Name && c.Index == this.Index; 
     } 
     return false; 
    } 
} 

在下面的Test方法中,第一比較結果arrayCompare1true和第二結果arrayCompare2false。兩者的比較結果都必須是真實的,但存在一個不正常的情況。我該如何解決這個問題?

測試代碼:

public void Test() 
{ 
    City c1 = new City("A", 1); 
    City c2 = new City("B", 2); 

    City[] arr1 = new City[] { c1, c2 }; 
    City[] arr2 = new City[] { c1, c2 }; 

    City[] arr3 = new City[] { new City("A", 1), new City("B", 2) }; 
    City[] arr4 = new City[] { new City("A", 1), new City("B", 2) }; 

    bool arrayCompare1 = arr1.SequenceEqual(arr2); 
    bool arrayCompare2 = arr3.SequenceEqual(arr4); 

    MessageBox.Show(arrayCompare1 + " " + arrayCompare2); 
} 
+3

這個條件沒用'this == null' – CodeNotFound

+0

感謝@CodeNotFound的迴應。你是對的。 –

回答

4

你需要以某種方式覆蓋的Object.Equals這樣的:

public override bool Equals(object other) 
{ 
    if (other is IGene) 
     return Equals((IGene)other); 
    return base.Equals(other); 
} 
+0

好吧,它工作。但是重寫的Equals方法不是由'IEquatable'接口實現的,它似乎來自'IEquatable'接口的'Equals'方法不用於數組比較。我需要確定從'IGene'接口繼承的類包含重寫的'Equals'方法。我怎樣才能做到這一點? –

+0

這種情況下沒有類實現IEquateable而是創建一個單獨的類來實現IEqualityComparer 然後將那個比較器通過SequenceEqual –

2

你需要覆蓋布爾等於(對象 OBJ)。最簡單的代碼:

public override bool Equals(object obj) 
    { 
     return Equals(obj as IGene); 
    } 
相關問題