C#接口详解:用Visual Studio 2019实现多态性

本文将通过一个使用 Visual Studio 2019 编写的 C# 代码示例,带您学习如何使用接口实现多态性。

代码示例csharpusing System;

// 定义接口interface IBirth{ void GiveBirth();}

interface ITalk{ void Talk();}

interface IWalk{ void Walk();}

interface IFly{ void Fly();}

interface IDeath{ void Die();}

// 定义类并实现接口class Human : IBirth, ITalk, IWalk, IDeath{ public void GiveBirth() { Console.WriteLine('Human gives birth.'); }

public void Talk()    {        Console.WriteLine('Human talks.');    }

public void Walk()    {        Console.WriteLine('Human walks.');    }

public void Die()    {        Console.WriteLine('Human dies.');    }}

class Dog : IBirth, IWalk, IDeath{ public void GiveBirth() { Console.WriteLine('Dog gives birth.'); }

public void Walk()    {        Console.WriteLine('Dog walks.');    }

public void Die()    {        Console.WriteLine('Dog dies.');    }}

class Parrot : IBirth, ITalk, IWalk, IFly, IDeath{ public void GiveBirth() { Console.WriteLine('Parrot gives birth.'); }

public void Talk()    {        Console.WriteLine('Parrot talks.');    }

public void Walk()    {        Console.WriteLine('Parrot walks.');    }

public void Fly()    {        Console.WriteLine('Parrot flies.');    }

public void Die()    {        Console.WriteLine('Parrot dies.');    }}

// 主程序class Program{ static void Main(string[] args) { Human human = new Human(); human.GiveBirth(); human.Talk(); human.Walk(); human.Die();

    Dog dog = new Dog();        dog.GiveBirth();        dog.Walk();        dog.Die();

    Parrot parrot = new Parrot();        parrot.GiveBirth();        parrot.Talk();        parrot.Walk();        parrot.Fly();        parrot.Die();

    Console.ReadLine();    }}

代码解析

  1. 定义接口: 我们定义了五个接口 IBirthITalkIWalkIFlyIDeath,分别代表生物的出生、说话、行走、飞行和死亡行为。

  2. 定义类并实现接口: 我们定义了三个类 HumanDogParrot,分别代表人类、狗和鹦鹉。每个类都实现了与其行为相符的接口,并具体定义了每个接口方法的行为。

  3. 主程序:Main 方法中,我们创建了 HumanDogParrot 对象,并调用了它们各自实现的接口方法。

总结

这段代码演示了如何使用接口来实现多态性。通过定义接口,我们可以规范类的行为,并通过实现接口方法来实现具体的功能。这种方式使得代码更加灵活和可扩展。


原文地址: https://www.cveoy.top/t/topic/bzN3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录