c# - 如何定义运算符==

标签 c#

给定类如下,

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/

相关文章:

c# - 从字符串数组列表转换为对象列表

c# - 如何使用 LINQ 确定特定属性值是否存在?

c# - 代码应该进行单元测试还是集成测试

c# - 根据可变数量的空格拆分字符串

c# - 为什么我的绑定(bind)失败?

c# - 基本身份验证和 SSL 失败的 Web 请求 (GET)

c# - 创建操作 head 标签的处理程序

c# - 将匿名类型转换为数组或数组列表。可以做吗

C# - XML 子节点到文本框

c# - 找不到 CodeDom 提供程序类型 "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider"