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

如何在C#中检查自定义类数组的相等性?,c#,arrays,equality,C#,Arrays,Equality,我有一个名为City的自定义类,这个类有一个Equals方法。当比较带有指定变量的数组时,SequenceEqual方法效果良好。比较包含格式化为new City()的元素的两个数组时会出现问题。结果是错误的 城市级: interface IGene : IEquatable<IGene> { string Name { get; set; } int Index { get; set; } } class City : IGene { string name

我有一个名为
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;
    }
}
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);
}

您需要覆盖对象。以某种方式如下:

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

您需要覆盖对象。以某种方式如下:

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

您需要重写bool Equals(objectobj)。最简单的代码添加:

    public override bool Equals(object obj)
    {
        return Equals(obj as IGene);
    }

您需要重写bool Equals(objectobj)。最简单的代码添加:

    public override bool Equals(object obj)
    {
        return Equals(obj as IGene);
    }

此条件无效
this==null
感谢@CodeNotFound的响应。你说得对。这个条件是无用的
this==null
感谢@CodeNotFound的响应。你说得对。好吧,它成功了。但是被重写的
Equals
方法不是由
IEquatable
接口实现的,而且来自
IEquatable
接口的
Equals
方法似乎不用于数组比较。我需要确保从
IGene
接口继承的类包含重写的
Equals
方法。我该怎么做?在这种情况下,不要让类实现IEQuatable,而是创建一个单独的类来实现IEqualityComparer,然后将该比较器传递给SequenceEqualOk,成功了。但是被重写的
Equals
方法不是由
IEquatable
接口实现的,而且来自
IEquatable
接口的
Equals
方法似乎不用于数组比较。我需要确保从
IGene
接口继承的类包含重写的
Equals
方法。我该怎么做?在这种情况下,不要让类实现IEQuatable,而是创建一个实现IEqualityComparer的单独类,然后将该比较器传递给SequenceEqual