类继承了抽象类,并使用相同的签名方法实现接口

本文关键字:方法 接口 实现 继承 抽象类 | 更新日期: 2023-09-27 18:11:04

我对这种具有相同签名方法的抽象类和接口的场景感到困惑。在推导课上会有多少定义?该呼叫将如何解决?

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签名定义方法,则可以有两个实现。看看关于隐式和显式实现的区别的问题。你的样品中也有一些错误

    在AbClass中
  • 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方法并覆盖它。

相关文章: