简体   繁体   English

C# - 用于覆盖“等于”的任何代码优化技术?

[英]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 ? LINQ或其他技术的任何其他选择给我快捷代码?

Update : 更新:

Moreover i gusess i have to override GetHasCode() too when i override "Equals". 此外,当我覆盖“等于”时,我也必须覆盖GetHasCode()。

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 )? SalesPerson的实例是否可以等于SalesManager的实例(可以从SalesPerson派生)?

The trouble is, the symmetric nature of equals gets in the way. 麻烦的是,equals的对称性质阻碍了它。 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. 我希望y.Equals(x)是假的 - 这意味着x.Equals(y)应该是假的。

This means the check in SalesPerson really needs to be: 这意味着SalesPerson的检查确实需要:

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. 请注意,我没有typeof(SalesPerson)进行比较,因为SalesManager的实现可能首先要调用此实现。

Of course, all of this complication goes away if SalesPerson is sealed... another reason for being very careful before introducing inheritance :) 当然,如果SalesPerson被密封,所有这些复杂性都会消失...在引入继承之前要非常小心的另一个原因:)

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. 非null的测试保证首先运行,因此在相等测试的其余部分中不会发生潜在的NullReferenceException。

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. 我建议使用反射器工具 ,直接从Microsoft的代码中学习最佳实践。

For example, System.Reflection.Module class equals function implementation: 例如, System.Reflection.Module类等于函数实现:

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. 编辑:将实现示例更改为Module类。

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. 我发现Resharper是一个非常有用的工具,用于“苦差事”这样的工作,当然可以帮助你专注于你想要实现的实现细节。

See here for more info. 有关详细信息,请参见此处 If there are alternatives I'm open to hear them. 如果有其他选择,我愿意听取他们的意见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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