给定类如下,
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 ((a.X == b.X) && (a.Y == b.Y));
}
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
}
更多信息 here .简而言之:
- 任何重载运算符 == 的类型也应该重载运算符 !=
- 任何重载运算符 == 的类型也应该重载 Equals
- 建议任何覆盖 Equals 的类也覆盖 GetHashCode
关于c# - 如何定义运算符==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5966272/