C#接口详解:用Visual Studio 2019实现多态性
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(); }}
代码解析
-
定义接口: 我们定义了五个接口
IBirth、ITalk、IWalk、IFly和IDeath,分别代表生物的出生、说话、行走、飞行和死亡行为。 -
定义类并实现接口: 我们定义了三个类
Human、Dog和Parrot,分别代表人类、狗和鹦鹉。每个类都实现了与其行为相符的接口,并具体定义了每个接口方法的行为。 -
主程序: 在
Main方法中,我们创建了Human、Dog和Parrot对象,并调用了它们各自实现的接口方法。
总结
这段代码演示了如何使用接口来实现多态性。通过定义接口,我们可以规范类的行为,并通过实现接口方法来实现具体的功能。这种方式使得代码更加灵活和可扩展。
原文地址: https://www.cveoy.top/t/topic/bzN3 著作权归作者所有。请勿转载和采集!