简体   繁体   English

C#继承与构造函数和覆写

[英]C# inheritance and constructors and overide

I'm testing this program for inheritance I have 3 classes ( animal,emu,kangaroo) and main class. 我正在测试此程序的继承性,我有3类(动物,e,袋鼠)和主类。

emu and kangaroo derived from Animal class. mu和袋鼠源自动物类。

when I try to run the program getting error Emu.Bird(), Kangaroo.Mamel() is not suitable method found to overide. 当我尝试运行出现错误Emu.Bird()的程序时,Kangaroo.Mamel()不适合覆盖。 I'm doing it by a random tutorial and not sure about the "override" and what exactly it does. 我正在通过随机教程进行操作,不确定“覆盖”及其确切功能。

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();
    }

Animal Class 动物类

 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);

    }
}

Emu Class 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);
    }

}

Kangaroo Class 袋鼠班

  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);
    }
}

The word override in coding means to replace the implementation of an existing method, ie overriding the previous method. 编码中的单词覆盖意味着替换现有方法的实现,即覆盖先前的方法。

So here in your case, the class that you are inheriting from doesn't have mamel or bird method. 因此,在这种情况下,您要继承的类没有mamel或bird方法。

Don't just read random articles..go by series of topics. 不要只是按系列主题阅读随机文章。 Refer a book or some tutorial series. 请参阅书籍或一些教程系列。

Check if you can pdf version of CLR via C# or you can also refer our ongoing tutorial series at CheezyCode 检查您是否可以通过C#生成CLR的 pdf版本,也可以在CheezyCode上参考我们正在进行的教程系列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM