【问题标题】:Interface for Child Class that Inherits from parent class without reimplementing parent class从父类继承而不重新实现父类的子类的接口
【发布时间】:2015-06-17 08:17:22
【问题描述】:

目前我有以下:

public class ChildClass : ParentClass
{...

ParentClass实现接口如下(我需要ParentClass被实例化,因此不能抽象):

public class ParentClass : IParentClass
{...

我还希望子类实现一个接口,以便我可以模拟这个类,但我希望 ParentClass 的继承成员对 ChildClass 接口可见。

因此,如果我在父类中有一个方法 MethodA(),我希望在使用 IChildClass 时能够调用此方法,而不仅仅是 ChildClass。

我能想到的唯一方法是重写 ChildClass 中的方法,在 IChildClass 中定义该方法,然后调用 base.MethodA() 但这似乎并不正确

【问题讨论】:

    标签: c# oop inheritance interface


    【解决方案1】:

    如果我对您的理解正确,您的意思是您的接口和类中都需要继承层次结构。

    这就是你实现这一目标的方式:

    public interface IBase 
    {
        // Defines members for the base implementations
    }
    
    public interface IDerived : IBase
    {
        // Implementors will be expected to fulfill the contract of
        // IBase *and* whatever we define here
    }
    
    public class Base : IBase
    {
        // Implements IBase members
    }
    
    public class Derived : Base, IDerived
    {
         // Only has to implement the methods of IDerived, 
         // Base has already implement IBase
    }
    

    【讨论】:

      【解决方案2】:

      我认为你可以做两件事。

      1) 您可以继承多个接口。 C# 支持这一点。只能从一个基类继承,但可以从多个接口继承。

      2) 你可以让你的接口相互继承。 IChildClass 接口可以继承自 IParentClass 接口。

      这有帮助吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-09
        • 2017-03-18
        • 2012-04-11
        • 2018-06-29
        相关资源
        最近更新 更多