从父类继承而没有重新实现父类

时间:2015-06-17 08:17:23

标签: c# oop inheritance interface

目前我有以下内容:

public class ChildClass : ParentClass
{...

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

public class ParentClass : IParentClass
{...

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

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

我能想到的唯一方法是覆盖ChildClass中的方法,在IChildClass中定义该方法,并调用base.MethodA(),但这看起来并不正确

2 个答案:

答案 0 :(得分:5)

如果我理解正确,那么你就是说你想在接口和类中使用继承层次结构。

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

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
}

答案 1 :(得分:2)

我认为你可以做两件事。

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

2)您可以使您的接口彼此继承。 IChildClass接口可以继承自IParentClass接口。

这有帮助吗?

相关问题