C# 编译器在实现 == 和 != 运算符记录定义时发出编译错误

C# compiler issues a compile error when implementing == and != operators record definitions

根据以下示例,我有一条记录:

public record MyData
{
   public string Id { get; set; }
   public string Code { get; set; }
   public string Description { get; set; }
   
   public bool operator ==(MyData d1, MyData d2)
   {
      return d1.Id == d2.Id;
   }

   public bool operator !=(MyData d1, MyData d2)
   {
      return d1.Id != d2.Id;
   }
}

这是我收到的错误消息,我不确定如何解决它!

error CS0111: Type 'MyData' already defines a member called 'op_Equality' with the same parameter types.

当我将 record 转换为 class 时,此问题已解决,但由于某些原因,我们必须继续使用 record。摆脱这个编译问题的解决方案是什么?

根据specs设计:

For records, the compiler generates the Equals method. In practice, the implementation of value equality in records is measurably faster

In class types, you could manually override equality methods and operators to achieve value equality, but developing and testing that code would be time-consuming and error-prone. Having this functionality built-in prevents bugs that would result from forgetting to update custom override code when properties or fields are added or changed.

这意味着您应该考虑与 struct 类型相比的性能优势,后者具有相同的等式语义但有其自身的缺点,例如,在装箱方面。

如果您希望自己的相等逻辑与运算符一起使用,您可以添加 public virtual bool Equals(T)public override int GetHashCode()。编译器生成的相等运算符在内部调用 virtual bool Equals(T),这是自动生成的,如果开发人员未覆盖则使用值相等。