本文主要是介绍C# 程序设计,设计抽象类Animal,具有类别、速度等属性,具有吃、叫、喜好等抽象方法;设计派生类Dog 、Cat实现抽象方法...比较对象的速度,并给出结果,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/// <summary>
/// 抽象类:动物
/// </summary>
public abstract class Animal {protected string type;protected int speed;public string Type => type;public int Speed => speed;public abstract void Talk();public abstract void Eat();public abstract void Love();public override string ToString() {return type;}
}
/// <summary>
/// 实现类:猫
/// </summary>
public class Cat:Animal {public Cat(string type,int speed) {this.type = type;this.speed = speed;}public override void Talk() {System.Console.WriteLine("喵喵");}public override void Eat() {System.Console.WriteLine("吃鱼");}public override void Love() {System.Console.WriteLine("捉老鼠");}
}
/// <summary>
/// 实现类:狗
/// </summary>
public class Dog:Animal {public Dog(string type, int speed) {this.type = type;this.speed = speed;}public override void Talk() {System.Console.WriteLine("汪汪");}public override void Eat() {System.Console.WriteLine("吃肉");}public override void Love() {System.Console.WriteLine("狩猎");}
}
using System;namespace _3_1 {class Program {static void Main(string[] args) {Animal cat = new Cat("波斯猫", 30);Animal dog = new Dog("猎犬", 60);//调用行为cat.Talk();cat.Eat();cat.Love();//调用行为dog.Talk();dog.Eat();//dog.Love();输出属性,重载ToStringPrintPropertys(cat);PrintPropertys(dog);比较Console.WriteLine($"速度更快的是:{(cat.Speed > dog.Speed ? cat.Type : dog.Type)}");Console.ReadLine();}static void PrintPropertys(Animal animal) {Console.WriteLine($"类型:{animal.Type}, 速度:{animal.Speed}");}}
}
运行结果:
这篇关于C# 程序设计,设计抽象类Animal,具有类别、速度等属性,具有吃、叫、喜好等抽象方法;设计派生类Dog 、Cat实现抽象方法...比较对象的速度,并给出结果的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!