Is there a complete IEquatable implementation reference?

前端 未结 5 528
猫巷女王i
猫巷女王i 2020-11-29 18:44

Many of my questions here on SO concerns IEquatable implementation. I found it being extremely difficult to implement correctly, because there are many hidden bugs in the na

5条回答
  •  攒了一身酷
    2020-11-29 19:12

    Upon reading MSDN, I'm pretty certain the best example of a proper implementation is in the IEquatable.Equals Method page. My only deviation is the following:

    public override bool Equals(Object obj)
    {
       if (obj == null) return base.Equals(obj);
    
       if (! (obj is Person))
          return false; // Instead of throw new InvalidOperationException
       else
          return Equals(obj as Person);   
    }
    

    For those wondering about the deviation, it derives from the Object.Equals(Object) MSDN page:

    Implementations of Equals must not throw exceptions.

提交回复
热议问题