How is inheritance implemented in C#?

In C#, inheritance is achieved by using the keyword “:”. Here is a simple example demonstrating how inheritance is implemented in C#.

// 定义一个基类
public class Animal
{
    public string Name { get; set; }

    public void Eat()
    {
        Console.WriteLine("Animal is eating");
    }
}

// 定义一个子类,继承自Animal基类
public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Dog is barking");
    }
}

class Program
{
    static void Main()
    {
        Dog dog = new Dog();
        dog.Name = "Tom";
        dog.Eat(); // 调用基类方法
        dog.Bark(); // 调用子类方法
    }
}

In the example above, Animal is a base class, Dog is a subclass, and the Dog class inherits from the Animal class. By using the keyword “:”, the Dog class can inherit from the Animal class, thus gaining access to the properties and methods of the Animal class. In the Main method, a Dog object is created and the Eat() method of the base class Animal and the Bark() method of the subclass Dog are called.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds