c# - 在基类中实现 IEquatable

标签 c# iequatable

我首先使用带有 EntityFramework 代码的 ASP.NET MVC。

我正在尝试为将保存到我的数据库中的所有对象创建一个基类(这里称为实体类)。

有没有在基类中实现IEquatable的好方法?在我的实现中,我检查了类型和 ID——这是一个好方法吗?这会始终返回最终的派生类型吗?中间 parent 呢?

对象

public abstract class Entity : IEquatable<Entity>
{
    public int ID { get; set; }
    public string Name { get; set; }

    public Entity(string Name)
    {
        this.Name = Name;
    }

    public override string ToString() { return Name; }
    public override int GetHashCode() { return ID.GetHashCode(); }
    public override bool Equals(object obj) { return this == (Entity)obj; }
    public bool Equals(Entity other) { return this == other; }
    public static bool operator ==(Entity x, Entity y) { return Object.ReferenceEquals(x, y) ? true : ((object)x == null || (object)y == null) ? false : (x.GetType() == y.GetType() && x.ID.Equals(y.ID)); }
    public static bool operator !=(Entity x, Entity y) { return !(x == y); }
}

public abstract class Content : Entity
{
    public Content(string Name) : base(Name)
    {

    }
}

public class Page : Content
{
            public string Body { get; set; }
    public Page(string Name) : base(Name)
    {

    }
}

public class User : Entity
{
    public User(string Name) : base(Name)
    {

    }
}

数据库

每个派生对象类型通常都存在于单独的数据库中。但是,会有一些对象具有共享主键的中间继承父对象。

假设有三个表,其中包含以下列: 实体

  • 内容
    • 身份证
    • 姓名
  • 页面
    • 身份证
    • 正文
  • 用户
    • 身份证
    • 姓名

因此,Page 和 Content 表共享一个主键。

最佳答案

  1. 无需实现 IEquitable,它不提供任何值(value)(既没有性能值(value),也没有可读性值(value))。
  2. 在您的比较中,您仅依靠引用相等性检查。您还应该检查 ID 是否相等。
  3. 您的 GetHashCode() 实现不是最优的,您还应该包括实体的类型。
  4. 您确定所有实体都将具有 Name 属性吗?在基类中,您应该包含存在于限界上下文的每个实体中的属性。

我在这里详细描述这个主题:Domain object base class .

关于c# - 在基类中实现 IEquatable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22596742/

相关文章:

c# - 为什么这个扩展方法适用于泛型而不适用于集合基类型?

c# - 使用计时器显示文本 3 秒?

c# - ControlBuilder 实现的通用 DropDown 丢失了所有属性

c# - 何时指定约束 `T : IEquatable<T>`,即使它不是严格要求的?

vb.net - 是否正确实现了 IEquatable?我应该总是覆盖 GetHashCode 吗?

c# - 通过 PHP 启动服务器端打印作业

c# - 如何从回收站获取已安装卷/磁盘的文件列表?

c# - 使 List<Student> 可与 IEquatable<Student> 区分

c# - 编译器选择错误的重载调用 IEquatable<T>.Equals

c# - 我应该如何实现 Object.GetHashCode() 以实现复杂的相等性?