繁体   English   中英

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

[英]tclass extends an abstract class and implements interface with same signature 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??? 
}

在默认情况下,只有一个实现,但是如果要定义带有void Iinterface.printMyName签名的方法,则可以有两个实现。 看一下关于隐式和显式实现之间的区别的 SO问题。 您的样本中也有一些错误

  • printMyName中的printMyName未标记为抽象,因此应具有主体。
  • 如果要使用抽象方法 -不能为私有方法

--

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

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

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方法,并在派生类中重写该方法。

暂无
暂无

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

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