简体   繁体   English

对实现通用接口的抽象类执行“保护的抽象替代”

[英]Perform a 'protected abstract override' for an abstract class which implements a generic interface

I have an interface which looks like this: 我有一个看起来像这样的界面:

public interface ISomeInterface<out TEntityA, TEntityB> 
    where TEntityA : ISomeEntityA
    where TEntityB : ISomeEntityB
{
    TEntityA SomeMethod(TEntityB entityB);
}  

On the other hand, I have a abstract class which implements this interface, so, using the intellisense the implementation looks this way: 另一方面,我有一个实现该接口的抽象类,因此,使用智能感知,实现看起来是这样的:

public abstract class BaseAbstractClass : ISomeInterface<EntityA, EntityB>
{
    public EntityA SomeMethod(EntityB entityB)
    {
        throw new NotImplementedException();
    }
}

Since EntityA and EntityB are both concrete implementations of ISomeEntityA and ISomeEntityB respectively, it seems that I'm forced to throw a NotImplementedException and this looks pretty dirty. 由于EntityAEntityB分别分别是ISomeEntityAISomeEntityB的具体实现,所以似乎我被迫抛出NotImplementedException ,这看起来很脏。

Being that you can't change the signature when you override a method, my question is: "Is there a way to perform a 'protected abstract override' in order to force the implementation of SomeMethod in the inherited classes of BaseAbstractClass ?" 由于无法在覆盖方法时更改签名,因此我的问题是: “是否有一种方法可以执行“受保护的抽象覆盖”,以便在BaseAbstractClass的继承类中强制执行SomeMethod

For more clarity, I want to do is something like this (It won't compile) : 为了更清楚,我想做的是这样的(它不会编译)

public abstract class BaseAbstractClass : ISomeInterface<EntityA, EntityB>
{
    public abstract override EntityA SomeMethod(EntityB entityB);
}

Why don't you call it something else? 你为什么不叫别的东西呢?

public abstract class BaseAbstractClass : ISomeInterface<EntityA, EntityB>
{
    protected abstract EntityA SomeMethodImpl(EntityB entityB);

    public EntityA SomeMethod(EntityB entityB) 
    {
        return SomeMethodImpl(entityB);
    }
}

Simply get rid of the override . 只需摆脱override This will compile: 这将编译:

public abstract class BaseAbstractClass : ISomeInterface<EntityA, EntityB>
{
    public abstract EntityA SomeMethod(EntityB entityB);
}

It's called an "abstract interface implementation". 这称为“抽象接口实现”。

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

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