IEquatable可以比较具有其他自定义对象的列表属性的自定义对象吗?

时间:2014-03-02 23:09:45

标签: c# .net

我想比较两个相同类型的自定义类对象。要比较的自定义类具有List属性,该属性用另一个自定义类型的项填充。继承IEquatable可以实现吗?

我无法弄清楚如何通过修改MSDN's code来比较包含自定义类型的List属性的类对象来完成这项工作。

我成功地从EqualityComparer class派生出一个单独的比较类(下面的代码),但我想在比较的实际类中实现比较能力。这是我到目前为止所做的:

编辑:这毕竟不起作用。我道歉 - 我一直在研究这个问题,我可能粘贴了不正确的示例代码。我正在努力寻找我的工作解决方案......

class Program
{
    static void Main(string[] args)
    {
     // Test the ContractComparer.

        Contract a = new Contract("Contract X", new List<Commission>() { new Commission(1), new Commission(2), new Commission(3) });
        Contract b = new Contract("Contract X", new List<Commission>() { new Commission(1), new Commission(2), new Commission(3) });

        ContractComparer comparer = new ContractComparer();

        Console.WriteLine(comparer.Equals(a, b));
    // Output returns True. I can't get this to return
        // True when I inherit IEquatable in my custom classes
        // if I include the list property ("Commissions") in my
        // comparison.

        Console.ReadLine();
    }
}

public class Contract
{
    public string Name { get; set; }
    public List<Commission> Commissions { get; set; }
    public Contract(string name, List<Commission> commissions)
    {
        this.Name = name;
        this.Commissions = commissions;
    }
}

public class Commission
{
    public int ID;
    public Commission(int id)
    {
        this.ID = id;
    }
}

public class ContractComparer : IEqualityComparer<Contract>
{

    public bool Equals(Contract a, Contract b)
    {
        //Check whether the objects are the same object.  
        if (Object.ReferenceEquals(a, b)) return true;

        //Check whether the contracts' properties are equal.  
        return a != null && b != null && a.Name.Equals(b.Name) && a.Commissions.Equals(b.Commissions);
    }

    public int GetHashCode(Contract obj)
    {
        int hashName = obj.Name.GetHashCode();
        int hashCommissions = obj.Commissions.GetHashCode();

        return hashName ^ hashCommissions;
    }
}

1 个答案:

答案 0 :(得分:2)

您必须为Commission实施某种比较器,例如通过实施Commission : IEquatable<Commission>,然后使用它:

... && a.Commissions.SequenceEqual(b.Commissions)