gpt4 book ai didi

c# - 如何在 C# 中检查自定义类数组的相等性?

转载 作者:太空宇宙 更新时间:2023-11-03 19:00:27 25 4
gpt4 key购买 nike

我有一个名为 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方法中,第一个比较结果arrayCompare1true,第二个结果arrayCompare2错误。两者比较结果必须为真,但存在异常情况。我该如何解决这个问题?

测试代码:

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.Equals:

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

关于c# - 如何在 C# 中检查自定义类数组的相等性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36817526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com