如何定义operator ==

鉴于课程如下,

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

如何定义重载运算符==以便我可以使用以下语句:

 Number n1 = new Number { X = 10, Y = 10 }; Number n2 = new Number { X = 100, Y = 100 }; if (n1 == n2) Console.WriteLine("equal"); else Console.WriteLine("not-equal"); 

//根据评论更新如下//

这是一个进一步的问题:在我看来,C#的运算符重载与C ++不同。 在C ++中,此重载运算符在目标类之外定义为独立函数。 在C#中,这个重载函数实际上已嵌入到目标类中。

有人可以就这个话题给我一些评论吗?

谢谢

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication3 { public class Number { public int X { get; set; } public int Y { get; set; } public Number() { } public Number(int x, int y) { X = x; Y = y; } public static bool operator==(Number a, Number b) { return ((aX == bX) && (aY == bY)); } public static bool operator !=(Number a, Number b) { return !(a == b); } public override string ToString() { return string.Format("X: {0}; Y: {1}", X, Y); } public override bool Equals(object obj) { var objectToCompare = obj as Number; if ( objectToCompare == null ) return false; return this.ToString() == obj.ToString(); } public override int GetHashCode() { return this.ToString().GetHashCode(); } } class Program { static void Main(string[] arg) { Number n1 = new Number { X = 10, Y = 10 }; Number n2 = new Number { X = 10, Y = 10 }; if (n1 == n2) Console.WriteLine("equal"); else Console.WriteLine("not-equal"); Console.ReadLine(); } } } 

 public static bool operator ==(YourClassType a, YourClassType b) { // do the comparison } 

更多信息在这里 。 简而言之:

  • 任何重载operator ==的类型也应该重载operator !=
  • 任何重载operator ==的类型也应该重写Equals
  • 建议任何覆盖Equals的类也会覆盖GetHashCode

来自MSDN文档 :

 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 ax == bx && ay == by && az == bz; } public static bool operator !=(ThreeDPoint a, ThreeDPoint b) { return !(a == b); } 

这是一个如何做的简短示例,但我强烈建议阅读重载等于()和运算符=(C#编程指南)的指南,以了解Equals()和==等之间的交互。

 public class Number { public int X { get; set; } public int Y { get; set; } public static bool operator ==(Number a, Number b) { // TODO } } 

自己超载操作员:

 public static bool operator ==(Number a, Number b) { // do stuff return true/false; }