我有一个名为as的自定义类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);
}
您需要重写Object.Equal如下所示:
public override bool Equals(object other)
{
if (other is IGene)
return Equals((IGene)other);
return base.Equals(other);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句