tclass扩展了一个抽象类,并使用相同的签名方法实现接口

时间:2015-09-04 07:03:06

标签: c# interface abstract-class

我对这种具有相同签名方法的抽象类和接口的情况感到困惑。派生阶段会有多少定义?如何解决通话?

public abstract class AbClass
{
    public abstract void printMyName();
}

internal interface Iinterface
{
    void printMyName();
}

public class MainClass : AbClass, Iinterface
{
    //how this methods will be implemented here??? 
}

2 个答案:

答案 0 :(得分:4)

默认情况下只有一个实现,但如果您使用void Iinterface.printMyName签名定义方法,则可以有两个实现。看看有关Difference between Implicit and Explicit implementations的问题。您的样本中也有一些错误

    AbClass中的
  • printMyName未标记为抽象,因此它 应该有身体。
  • 如果你想拥有abstract method - 它不能是私人的

-

public abstract class AbClass
{
    public abstract void printMyName();
}

internal interface Iinterface
{
    void printMyName();
}

public class MainClass : AbClass, Iinterface
{
    //how this methods will be implemented here??? 
    public override void printMyName()
    {
        Console.WriteLine("Abstract class implementation");
    }

    //You can implement interface method using next signature
    void Iinterface.printMyName()
    {
        Console.WriteLine("Interface implementation");
    }
}

public class MainClass_WithoutExplicityImplementation : AbClass, Iinterface
{
    //how this methods will be implemented here??? 
    public override void printMyName()
    {
        Console.WriteLine("Abstract class and interface implementation");
    }
}

使用示例

var mainInstance = new MainClass();
mainInstance.printMyName();      //Abstract class implementation
Iinterface viaInterface = mainInstance;
viaInterface.printMyName();      //Interface implementation


var mainInstance2 = new MainClass_WithoutExplicityImplementation();
mainInstance2.printMyName();      //Abstract class and interface implementation
Iinterface viaInterface = mainInstance2;
viaInterface.printMyName();      //Abstract class and interface implementation

答案 1 :(得分:0)

您可以在具体类中省略接口的实现,因为基类已经实现了它。但是,您也可以明确地实现接口,这意味着您可以“覆盖”基础(抽象)类中的行为(覆盖不是真正的正确单词)。这进一步期望将您的实例explicitky转换为接口以调用该方法:

public class MainClass : AbClass, Iinterface
{
    //how this methods will be implemented here??? 
    void Iinterface.printMyName()
    {
        throw new NotImplementedException();
    }
}

您可以致电此cia ((Iinterface(myMainClassInstance).printMyName()。如果您调用myMainClassInstance.printMyName,则会调用基本实现。

如果您想支持基类中的基本实现,您可以创建方法virtual并在派生类中覆盖它。

相关问题