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

时间:2016-04-23 23:15:52

标签: 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;
    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,第二个结果arrayCompare2false。两个比较结果必须为真,但存在正常的结果。我该如何解决这个问题?

测试代码:

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);
}

2 个答案:

答案 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);
    }