How to define the operator ==

后端 未结 4 536
执笔经年
执笔经年 2021-01-22 21:37

Given the class as follows,

public class Number
{
  public int X { get; set; }
  public int Y { get; set; }
}

How to define an overload operato

相关标签:
4条回答
  • 2021-01-22 21:55

    overload the operator yourself:

    public static bool operator ==(Number a, Number b)
    {
        // do stuff
        return true/false;
    }
    
    0 讨论(0)
  • 2021-01-22 22:03

    Here is a short example of how to do it, but I very strongly recommend reading Guidelines for Overloading Equals() and Operator == (C# Programming Guide) to understand the interaction between Equals() and == and so on.

    public class Number
    {
      public int X { get; set; }
      public int Y { get; set; }
    
      public static bool operator ==(Number  a, Number b)
      {
        // TODO
      }
    }
    
    0 讨论(0)
  • 2021-01-22 22:04

    From the MSDN Docs:

    public static bool operator ==(ThreeDPoint a, ThreeDPoint b)
    {
        // If both are null, or both are same instance, return true.
        if (System.Object.ReferenceEquals(a, b))
        {
            return true;
        }
    
        // If one is null, but not both, return false.
        if (((object)a == null) || ((object)b == null))
        {
            return false;
        }
    
        // Return true if the fields match:
        return a.x == b.x && a.y == b.y && a.z == b.z;
    }
    
    public static bool operator !=(ThreeDPoint a, ThreeDPoint b)
    {
        return !(a == b);
    }
    
    0 讨论(0)
  • 2021-01-22 22:15
    public static bool operator ==(YourClassType a, YourClassType b)
    {
        // do the comparison
    }
    

    More information here. In short:

    • Any type that overloads operator == should also overload operator !=
    • Any type that overloads operator == should also should override Equals
    • It is recommended that any class that overrides Equals also override GetHashCode
    0 讨论(0)
提交回复
热议问题