简体   繁体   English

接口继承和抽象方法覆盖

[英]Interface inheritance and abstract method overriding

Let's say we have a hierarchy of interfaces: IBaseThing<T> and IChildThing:IBase<ChildThing> . 假设我们有一个接口层次结构: IBaseThing<T>IChildThing:IBase<ChildThing> Also there are two classes like this: 还有两个这样的类:

internal abstract class Base<T>
{
    public abstract IBaseThing<T> Thing {get;}
}

and

internal class Concrete:Base<ChildThing>
{
    public override IChildThing Thing
    {
        get
        {
            return GetChildThing();
        }
     }
}

What will happen is as bellow: 将会发生的事情如下:

'Concrete' does not implement inherited abstract member 'Base.get' 'Concrete'不实现继承的抽象成员'Base.get'

I want to skip casting (IChildThing)this.Thing all over Concrete class. 我想跳过cast (IChildThing)this.Thing遍布Concrete类。 What I supposed to do? 我应该怎么办?

Try this solution: 尝试此解决方案:

public interface IBaseThing {}

public interface IChildThing : IBaseThing {}

internal abstract class Base<T> where T : IBaseThing
{
    public abstract T Thing {get;}
}

internal class Concrete:Base<IChildThing>
{
    public override IChildThing Thing
    {
        get
        {
            return GetChildThing();
        }
     }

     public IChildThing GetChildThing()
     {  
        // Your impelementation here...
        return null;
     }
}

You can't do that. 你不能这样做。 The type system is rightly objecting to you attempting to change the method type in the overriding class. 类型系统正在反对您尝试更改覆盖类中的方法类型。 IChildThing might derive from IBaseThing, but it is not the same thing. IChildThing可能来自IBaseThing,但它不是一回事。 For example, you might add some more methods to IChildThing later on. 例如,您可以稍后再向IChildThing添加一些方法。 Then one class (Concrete) would be promising a returned object with a different signature than the base class - that's a type error. 然后,一个类(Concrete)将承诺返回的对象具有与基类不同的签名 - 这是类型错误。

If you need to refer to a IChildThing in some cases, how about something like: 如果在某些情况下需要引用IChildThing,请执行以下操作:

internal class Concrete : Base<ChildThing>
{
    public override IBaseThing<ChildThing> Thing
    {
        get { return ChildThing; }
    }

    public IChildThing ChildThing { get; set; }
}

If all you have is a Base though, then you can't get at the IChildThing safely. 如果你拥有的只是一个Base,那么你就无法安全地进入IChildThing。 That's the nature of a strongly typed system like this. 这就是像这样的强类型系统的本质。 If that's a problem, then if you gave a more concrete example I might be able to suggest how to restructure to avoid that problem. 如果这是一个问题,那么如果你给出一个更具体的例子,我可能会建议如何重组以避免这个问题。

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

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