【发布时间】:2021-05-03 08:58:11
【问题描述】:
为什么不允许我们做以下记录
abstract record AA
{
public abstract bool Equals(AA other);
}
record BB:AA
{
public override bool Equals(AA other)// error as it is already implemented
{
//do some thing
}
}
虽然这对于课程来说是完全可以接受的?
abstract class AA
{
public abstract bool Equals(AA other);
}
class BB:AA
{
public override bool Equals(AA other)
{
//do some thing
}
}
顺便说一句,我正在执行此实现以强制 Equals 检查级联到其派生类。
编辑:只是为了说明我为什么对此感兴趣,因为我目前正在为 IEquatable 创建一个library/autogenerator。
Edit/Info 2:基于cmets,我做了一些测试。由于无法覆盖抽象的 Equals 记录方法,因此我尝试保持原样。
public abstract record AA
{
public int Prop1 { get; set; }
public string? Prop2 { get; set; }
public string? Prop5 { get; set; }
public abstract bool Equals(AA? other);
}
public record BB : AA
{
public string? Prop3 { get; set; }
}
结果我得到一个错误 System.BadImageFormatException: Bad IL format.
总而言之,记录上的抽象 Equals 方法不仅是一种不必要的实现,而且也是一种糟糕的实现。
【问题讨论】: