我有一个名为City
的自定义类,此类有Equals
方法。将数组与赋值变量进行比较时,SequenceEqual
方法很有效。比较包含格式为new City()
的元素的两个数组时会发生此问题。结果是假的。
城市类:
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);
}
答案 0 :(得分:4)
你需要以某种方式覆盖Object.Equals:
public override bool Equals(object other)
{
if (other is IGene)
return Equals((IGene)other);
return base.Equals(other);
}
答案 1 :(得分:2)
您需要覆盖bool Equals( object obj)。最简单的代码:
public override bool Equals(object obj)
{
return Equals(obj as IGene);
}