【问题标题】:Should I create an interface for abstract class?我应该为抽象类创建一个接口吗?
【发布时间】:2023-03-08 01:18:01
【问题描述】:

是否有任何实际理由为抽象类创建接口?我遇到过这样的事情:

public interface IEntity<T> 
{
    T Id { get; set; }
}

public abstract class BaseEntity { 
}

public abstract class Entity<T> : BaseEntity, IEntity<T> 
{
    public virtual T Id { get; set; }
}

我真的不明白这和这段代码有什么区别,因为 IEntity 不是我应该多次使用的东西:

public abstract class BaseEntity { 
}

public abstract class Entity<T> : BaseEntity
{
    public virtual T Id { get; set; }
}

谢谢!

【问题讨论】:

标签: c# entity-framework code-first


【解决方案1】:

由于BaseEntity 类确实添加了方法的任何属性,是的,它与接口完全不同。该接口定义了一个T 类型的属性Id,并且该接口(合同)可以在您的应用程序的其他位置使用。

现在的基类是无用的恕我直言。

为您实现接口的基类是可用的,如下所示:

public interface IEntity<T> {
    T Id { get; set; }
}

public abstract class BaseEntity<T>: IEntity<T> { 
    public virtual T Id { get; set; }
}

public abstract class Entity<T> : BaseEntity<T> {
    // No need to implement the Id property, we already have it inherited
}

【讨论】:

    【解决方案2】:

    这是我想知道的正确答案:c# Abstract Class implementing an Interface

    感谢大家的帮助。

    【讨论】:

      猜你喜欢
      • 2017-11-04
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 2020-05-03
      • 1970-01-01
      相关资源
      最近更新 更多