tclass 扩展抽象 class 并使用相同的签名方法实现接口

tclass extends an abstract class and implements interface with same signature method

我对抽象 class 和具有相同签名方法的接口的这种情况感到困惑。推导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??? 
}

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

    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

您可以在具体 class 中省略接口的实现,因为基础 class 已经实现了它。但是,您也可以显式实现接口,这意味着您可以 "override" 基础(抽象)class 的行为(此处重写不是真正的正确词)。这进一步期望将您的实例显式转换为调用该方法的接口:

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

你可以称这个为 cia ((Iinterface(myMainClassInstance).printMyName()。如果您调用 myMainClassInstance.printMyName 但是会调用基础实现。

如果你想在你的 base-class 中支持一个 base-implementation,你可以制作方法 virtual 并在你的派生 class.[=14= 中覆盖它]