简体   繁体   English

我应该为抽象类创建接口吗?

[英]Should I create an interface for abstract class?

Is there any practial reason to create interface for abstract class? 是否有任何实际的理由为抽象类创建接口? I encountered such thing: 我遇到过这样的事情:

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; }
}

and i really don't understand what is the difference between that and this code, because IEntity is not a thing i whould use more than once: 我真的不明白这和这段代码有什么区别,因为IEntity不是我应该多次使用的东西:

public abstract class BaseEntity { 
}

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

Thanks! 谢谢!

Since the BaseEntity class does actually add any properties of methods, yes, it is completely different from the interface. 由于BaseEntity类确实添加了方法的任何属性,是的,它与接口完全不同。 The interface defines a property Id of type T , and that interface (contract) can be used in other locations in your application. 该接口定义了类型为T的属性Id ,该接口(契约)可以在应用程序的其他位置使用。

The base class as it is now, is useless IMHO. 现在的基类是无用的恕我直言。

A base class which would implement the interface for you is something that would be usable, like this: 为您实现接口的基类是可用的,如下所示:

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
}

Here is the same thing with correct answer that i wanted to know: c# Abstract Class implementing an Interface 以下是我想知道的正确答案: c#Abstract Class实现一个接口

Thanks everyone for help. 谢谢大家的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在这种情况下应该使用接口还是抽象类? - Should I use an interface or abstract class in this scenario? C# - 我应该使用什么,接口,抽象类或两者? - C# - What should I use, an Interface, Abstract class, or Both? 我应该创建一个接口并模拟此类吗 - Should I create a interface and mock this class 我应该为界面中的每个按钮创建一个类吗? - Should i create a Class for each button in the interface? 无法创建抽象类或接口的实例,但它不是抽象类,也不是接口? - Cannot create an instance of the abstract class or interface, but it is not an abstract class and it's not an interface? 无法在接口方法中创建抽象类的实例 - unable to create instance of abstract class in interface method 从抽象引用创建接口+类包装器 - Create interface + Class wrapper from abstract references 无法创建抽象类或接口的实例 - Cannot create an instance of the abstract class or interface 无法使用类型创建抽象类或接口接口的实例 - Cannot create an instance of the abstract class or interface interface with type 如何创建一个 List(of T),其中 T 是 (T) 的接口,List 的内容继承了一个实现 T 接口的抽象类 - How can I create a List(of T) where T is an interface of (T) and the contents of the List inherit an Abstract class that implements the interface of T
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM