简体   繁体   中英

C# - Any Code optimization technique for Overriding “Equals”?

Normally ( Based on my understanding ) i have to follow a lot of steps to

override the "Equals" to check the state of the object.

Example :

    public override bool Equals(object obj)
     {
       if (obj is SalesPerson && obj != null)
       {

         SalesPerson temp;

         temp = (SalesPerson)obj;

           if (temp.fName == this.fName && temp.lName == this.fName 
              && temp.personAge == this.personAge )
              {

                 return true;
              }

          else
          {
            return false;
          }

      }
       return false;
     }

Any other alternative like LINQ or other techniques gives me shortcut code ?

Update :

Moreover i gusess i have to override GetHasCode() too when i override "Equals".

All the answers so far seem mostly fine to me. However, you should carefully consider what you want equality to mean in an inheritance hierarchy. Can an instance of just SalesPerson be equal to an instance of SalesManager (which would derive from SalesPerson )?

The trouble is, the symmetric nature of equals gets in the way. Suppose we have:

SalesPerson x = new SalesPerson { ... };
SalesManager y = new SalesManager { ... };

I'd expect y.Equals(x) to be false - which means that x.Equals(y) ought to be false too.

This means the check in SalesPerson really needs to be:

public override bool Equals(object obj)
{
    SalesPerson salesPerson = obj as SalePerson;
    if (salesPerson == null) return false;
    return salesPerson.GetType() == this.GetType() &&
           salesPerson.fName == this.fName && 
           salesPerson.lName == this.fName && 
           salesPerson.personAge == this.personAge;
}

Note that I'm not comparing with typeof(SalesPerson) as the implementation in SalesManager would probably want to call up to this implementation first.

Of course, all of this complication goes away if SalesPerson is sealed... another reason for being very careful before introducing inheritance :)

This looks neater:

public override bool Equals(object obj)
{
  SalesPerson salesPerson = obj as SalePerson;
  if(salesPerson == null) return false;
  return salesPerson.fName == this.fName && 
         salesPerson.lName == this.fName && 
         salesPerson.personAge == this.personAge;
}

And of course if you really wanted to compact it into a single line you could use:

public override bool Equals(object obj)
{
  SalesPerson salesPerson = obj as SalePerson;

  return (salesPerson != null) &&
         (salesPerson.fName == this.fName && 
         salesPerson.lName == this.fName && 
         salesPerson.personAge == this.personAge);
}

The test for non-null is guaranteed to run first and therefore no potential NullReferenceException can occur in the rest of the equality test.

You code seems very overcomplicated. I'd replace it with this:

public override bool Equals(object obj)
     {

    SalesPerson temp = obj as SalesPerson;
        if(temp == null) return false;

    return temp.fName == this.fName && temp.lName == this.fName 
              && temp.personAge == this.personAge;
     }

You could then write some operators == != etc..

I recommend to use the reflector tool and learn best practices directly from Microsoft's code.

For example, System.Reflection.Module class equals function implementation:

public override bool Equals(object o)
{
    if (o == null)
    {
        return false;
    }
    if (!(o is Module))
    {
        return false;
    }
    Module internalModule = o as Module;
    internalModule = internalModule.InternalModule;
    return (this.InternalModule == internalModule);
}

EDIT: Changed the implementation example to Module class.

I find Resharper a very useful tool for 'drudge' work such as this, and can certainly help you focus on what you are trying to achieve over the implementation detail.

See here for more info. If there are alternatives I'm open to hear them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM