比较对象的平等

时间:2011-02-23 09:32:29

标签: c#

我有这样的代码:

 public bool AreSame(CreditProposal creditProposal)
    {
        if (!ContractingParty.Equals(creditProposal.ContractingParty))
            return false;
        if (!UltimateParent.Equals(creditProposal.UltimateParent))
            return false;
        if (!Rebound.Equals(creditProposal.Rebound))
            return false;
        if (!ContactPerson.Equals(creditProposal.ContactPerson))
            return false;
        if (!DateOfVisit.Equals(creditProposal.DateOfVisit))
            return false;
      .... and so on 10 more times

有没有办法更简洁?或者这是否意味着我陷入了反思地狱?

2 个答案:

答案 0 :(得分:4)

覆盖Equals方法。

检查this on MSDN

注意If you implement ==, you must implement !=

答案 1 :(得分:2)

处理这种情况的本能方法是覆盖Object.Equals(Object)方法并为您的类型实施IEquatable<T>

但是,覆盖Object.Equals会提示您也覆盖Object.GetHashCode(),这要做得更加困难。最值得注意的是,GetHashCode()每次在同一实例上调用时必须返回相同的值,并且必须为两个被认为相等的对象返回相同的值。如果你的类型是可变的,这将成为一个真正的痛苦。 (事实上​​,GetHashCode()很难正确实现,StackOverflow上有一个完整的标记:https://stackoverflow.com/questions/tagged/gethashcode

Equals的静态实现通常如下所示:

public static bool Equals(CreditProposal proposalA, CreditProposal proposalB)
{
    // Check whether both values are null.
    if(object.ReferenceEquals(proposalA, null) 
        && object.ReferenceEquals(proposalB, null))
    {
        return true;
    }

    // Check whether either value is null.
    if(object.ReferenceEquals(proposalA, null) 
        || object.ReferenceEquals(proposalB, null))
    {
        return false;
    }

    // Check whether hashcodes are different.
    if(proposalA.GetHashCode() != proposalB.GetHashCode())
    {
        return false;
    }

    // Check for value equality.
    return Party.Equals(
            proposalA.ContractingParty, 
            proposalB.ContractingParty)
        && ParentProposal.Equals(
            proposalA.UltimateParent, 
            proposalB.UltimateParent);
        // Add more conditions for equality here.
}

您可以从所有实例方法中调用此实现。