Skip to main content
 首页 » 编程设计

c#之tclass 扩展一个抽象类并使用相同的签名方法实现接口(interface)

2024年02月05日10sharpest

我对抽象类和接口(interface)具有相同签名方法的这种情况感到困惑。派生类中会有多少个定义?调用将如何解决?

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 的问题.你的样本也有一些错误

    AbClass 中的
  • printMyName 未标记为抽象,因此它 应该有 body 。
  • 如果你想要 abstract method - 它不能是私有(private)的

-

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