簡體   English   中英

C#繼承與構造函數和覆寫

[英]C# inheritance and constructors and overide

我正在測試此程序的繼承性,我有3類(動物,e,袋鼠)和主類。

mu和袋鼠源自動物類。

當我嘗試運行出現錯誤Emu.Bird()的程序時,Kangaroo.Mamel()不適合覆蓋。 我正在通過隨機教程進行操作,不確定“覆蓋”及其確切功能。

static void Main(string[] args)
    {
        Emu e = new Emu("Emu","Brown", "is a bird");

        Console.WriteLine();

        Kangaroo k = new Kangaroo("Kangaroo","Dark Brown", "Is a mamel" );

        Console.ReadLine();
    }

動物類

 class Animal
{
    public string name;
    public string colour;

    public Animal(string MyName,string MyColour)
    {
        name = MyName;
        colour = MyColour;
    }

    public virtual void Show()
    {
        Console.WriteLine("Name: "+ name);
        Console.WriteLine("Colour: "+ colour);

    }
}

mu類

 class Emu:Animal
{
    public string bird;

    public Emu(string name,string colour, string eBird) : base(MyName,MyColour)
    {
        bird = eBird;
    }

    public override void Bird()
    {
        base.Show();
        Console.WriteLine(bird);
    }

}

袋鼠班

  class Kangaroo:Animal
{
    public string mamel;


    public Kangaroo(string name,string colour, string Mamel) : base(MyName,MyColour)
    {
        mamel = Mamel;
    }

    public override void Mamel()
    {
        base.Show();
        Console.WriteLine("Is a bird or Mamel ? " + mamel);
    }
}

編碼中的單詞覆蓋意味着替換現有方法的實現,即覆蓋先前的方法。

因此,在這種情況下,您要繼承的類沒有mamel或bird方法。

不要只是按系列主題閱讀隨機文章。 請參閱書籍或一些教程系列。

檢查您是否可以通過C#生成CLR的 pdf版本,也可以在CheezyCode上參考我們正在進行的教程系列

暫無
暫無

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

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