簡體   English   中英

tclass擴展了一個抽象類,並使用相同的簽名方法實現了接口

[英]tclass extends an abstract class and implements interface with same signature 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??? 
}

在默認情況下,只有一個實現,但是如果要定義帶有void Iinterface.printMyName簽名的方法,則可以有兩個實現。 看一下關於隱式和顯式實現之間的區別的 SO問題。 您的樣本中也有一些錯誤

  • printMyName中的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方法,並在派生類中重寫該方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM