开发者

Equality comparing objects

I have code like this:

 public bool AreSame(CreditProposal creditProposal)
    {
        if (!ContractingParty.Equals(creditProposal.ContractingParty))
            return false;
        if (!UltimateParent.Equals(creditProposal.Ult开发者_StackOverflow中文版imateParent))
            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

Is there a way to do this more concise? Or will that mean I get into reflection hell?


Override Equals method.

Check this on MSDN

And notice If you implement ==, you must implement !=.


The instinctive way to handle this situation is to override the Object.Equals(Object) method and implement IEquatable<T> for your type.

However, overriding Object.Equals will prompt you to also override Object.GetHashCode(), which is a lot harder to do correctly. Most notably, GetHashCode() must return the same value each time it is called on the same instance, and must return the same value for two objects which are considered equal. If your type is mutable, this becomes a real pain. (In fact, GetHashCode() is so difficult to implement correctly, there's a whole tag for it on StackOverflow: https://stackoverflow.com/questions/tagged/gethashcode)

The static implementation for Equals usually looks like this:

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.
}

You would call this implementation from all your instance methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜