简体   繁体   English

我可以强制子类实现接口吗?

[英]Can I Enforce a Subclass to Implement an Interface?

I have a base class, say named B .我有一个基类,比如名为B I have two derived classes, D1 and D2 .我有两个派生类, D1D2

Looks like:好像:

public abstract class B
{
    public abstract void DoSomething();
}

public class D1 : B
{
    public override void DoSomething() { ... }
}

public class D2 : B
{
    public override void DoSomething() { ... }
}

Now, I created a new interface IDeepCopyable<T> which has one method Clone() :现在,我创建了一个新接口IDeepCopyable<T> ,它有一个方法Clone()

public interface IDeepCopyable<T>
{
    T Clone();
}

I want to force each subclass too implement this interface with the base class (ie IDeepCopyable<B> .我想强制每个子类也用基类(即IDeepCopyable<B>实现这个接口。

If I try to leave B 's declaration as-is but just inherit from ('implement' is a more accurate term?) IDeepCopyable<T> , such as:如果我尝试保留B的声明原样但只是继承自('implement' 是一个更准确的术语?) IDeepCopyable<T> ,例如:

public abstract class B : IDeepCopyable<B>

Then to implement it in the derived classes (either implicitly or explicitly), the compiler gives me an error message " B does not implement interface member IDeepCopyable<B>.Clone() ".然后为了在派生类中实现它(隐式或显式),编译器给我一条错误消息“ B没有实现接口成员IDeepCopyable<B>.Clone() ”。

I can, of course, create an abstract method whose name is identical to the interface's method's name, but I find that ugly.当然,我可以创建一个抽象方法,其名称与接口的方法名称相同,但我觉得这很难看。 Why to redeclare the method?为什么要重新声明方法?

Can I, in any way, leave that as wanted?无论如何,我可以随心所欲吗?

I see that VS2019 has an option "Implement interface abstractly" so I think that the answer is no, but A) I want to be sure.我看到 VS2019 有一个选项“抽象地实现接口”,所以我认为答案是否定的,但是 A)我想确定。 B) If so, is there a design concept behind this behavior, or is it just a bug in C# design? B)如果是这样,这种行为背后是否有设计概念,或者它只是 C# 设计中的一个错误?

Thanks in advance.提前致谢。

I can, of course, create an abstract method whose name is identical to the interface's method's name, but I find that ugly.当然,我可以创建一个抽象方法,其名称与接口的方法名称相同,但我觉得这很难看。

That's the way to go.这就是要走的路。 Your base class implements the interface.您的基类实现了该接口。 Hence it has to fulfil it.因此它必须履行它。 It can do this by implementing the method concretely (which is not desired here) or the base class can force its inheritors to do so by declaring the method abstractly.它可以通过具体实现方法(这里不需要)来做到这一点,或者基类可以通过抽象地声明方法来强制其继承者这样做。

You say that's ugly, well I think it's just explicit .你说这很丑,我认为这只是露骨的 Anyway, there's no way around this ;-)无论如何,没有办法解决这个问题;-)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM