C#中怎么实现多态性


在C#中实现多态性一般通过继承和接口实现。具体方法如下:

    继承:通过创建一个父类和多个子类,子类继承父类的特性,并且可以重写父类的方法来实现多态性。例如:
class Animal{public virtual void MakeSound(){Console.WriteLine("Animal makes a sound");}}class Dog : Animal{public override void MakeSound(){Console.WriteLine("Dog barks");}}class Cat : Animal{public override void MakeSound(){Console.WriteLine("Cat meows");}}Animal myDog = new Dog();Animal myCat = new Cat();myDog.MakeSound(); // Output: Dog barksmyCat.MakeSound(); // Output: Cat meows
    接口:通过定义一个接口,然后让多个类实现这个接口,实现接口方法的多态性。例如:
interface IShape{double GetArea();}class Circle : IShape{public double Radius { get; set; }public double GetArea(){return Math.PI * Radius * Radius;}}class Rectangle : IShape{public double Width { get; set; }public double Height { get; set; }public double GetArea(){return Width * Height;}}IShape myCircle = new Circle() { Radius = 5 };IShape myRectangle = new Rectangle() { Width = 5, Height = 10 };Console.WriteLine(myCircle.GetArea()); // Output: 78.54Console.WriteLine(myRectangle.GetArea()); // Output: 50

通过以上两种方法,可以实现不同类对象对同一个方法的调用,实现多态性。


上一篇:php读取zip内目录要注意哪些事项

下一篇:r语言中怎么进行因子分析


C#
Copyright © 2002-2019 测速网 https://www.inhv.cn/ 皖ICP备2023010105号 城市 地区 街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!
热门搜索