2015-09-04 40 views
1

界面我很困惑与该场景的抽象类和接口具有相同签名的方法。在派生类中有多少个定义?该呼叫将如何解决?tclass扩展一个抽象类,实现了用相同的签名方法

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??? 
} 
+0

您必须使用显式方法重写。最多只有两个定义。例如:第一种方法。 'AbClass.printMyName(){console.writeln(“我是AbClass”)};'。 第二种方法:'Iinterface.printMyName(){console.writeln(“I am Iinterface”)};' –

回答

4

将有默认情况下只有一个实现,但你可以有两种实现,如果你会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 
0

可以内ommit接口的实现你的具体类,因为基类已经实现了它。不过,你也可以明确地实现接口,这意味着你可以“覆盖”你的基类(抽象)类的行为(重写在这里不是真正的正确的单词)。这进一步预计,投下您的实例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并在你的派生类中覆盖它。

相关问题