鉴于课程如下,
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();
}
}
}
答案 0 :(得分:11)
public static bool operator ==(YourClassType a, YourClassType b)
{
// do the comparison
}
更多信息here。简而言之:
答案 1 :(得分:1)
来自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);
}
答案 2 :(得分:1)
以下是如何执行此操作的简短示例,但我强烈建议阅读Guidelines for Overloading Equals() and Operator == (C# Programming Guide)以了解Equals()和==等之间的交互。
public class Number
{
public int X { get; set; }
public int Y { get; set; }
public static bool operator ==(Number a, Number b)
{
// TODO
}
}
答案 3 :(得分:0)
自己过载操作员:
public static bool operator ==(Number a, Number b)
{
// do stuff
return true/false;
}