12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
编程知识 时间:2024-12-04 13:01:49
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
在C#中实现多态性一般通过继承和接口实现。具体方法如下:继承:通过创建一个父类和多个子类,子类继承父类的特性,并且可以重写父类的方法来实现多态性。例如:class Animal{public
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
在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
通过以上两种方法,可以实现不同类对象对同一个方法的调用,实现多态性。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19