C#重载==和!=

时间:2022-01-05 03:45:31

  public int P1 { get; set; }

  public int P2 { get; set; }

  public static bool operator !=(A a1, A a2)
  {
    return !a1.Equals(a2);
  }

  public static bool operator ==(A a1, A a2)
  {
    return a1.Equals(a2);
  }  

  

  public override bool Equals(object obj)
  {
    // If parameter is null return false.
    if(obj == null)
    {
      return false;
    }  

    // If parameter cannot be cast to Settings return false.
            A a2 = obj as A;
    if((System.Object)a2 == null)
    {
      return false;
    }

    // Return true if the fields match:
    if (P1 != a2.P1 || P2 != a2.P2)
      return false;
    else
      return true;
     }

  public override int GetHashCode()
  {
    return P1;
  }