我有一個名爲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
方法中,第一比較結果arrayCompare1
是true
和第二結果arrayCompare2
是false
。兩者的比較結果都必須是真實的,但存在一個不正常的情況。我該如何解決這個問題?
測試代碼:
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);
}
這個條件沒用'this == null' – CodeNotFound
感謝@CodeNotFound的迴應。你是對的。 –