2015-09-04 41 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並在你的派生類中覆蓋它。

相關問題