How to define the operator ==

后端 未结 4 538
执笔经年
执笔经年 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 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);
    }
    

提交回复
热议问题