---------------------------------------父类Animals类---------------------------------------
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace JD.entity 8 { 9 /// <summary> 10 /// 动物类 11 /// </summary> 12 public class Animals 13 { 14 /// <summary> 15 /// 名字 16 /// </summary> 17 public string Name { get; set; } 18 /// <summary> 19 /// 颜色 20 /// </summary> 21 public string Color { get; set; } 22 public Animals(string name,string color) 23 { 24 this.Name = name; 25 this.Color = color; 26 } 27 } 28 }
Animals
---------------------------------------子类Cat类---------------------------------------
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace JD.entity 8 { 9 /// <summary> 10 /// 猫类 11 /// </summary> 12 public class Cat:Animals 13 { 14 public Cat(string name ,string color):base(name,color) 15 { 16 17 } 18 public void Bark() 19 { 20 Console.WriteLine("是{0}猫{1},喵喵",base.Color,base.Name); 21 } 22 } 23 }
Cat
---------------------------------------子类Dog类---------------------------------------
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace JD.entity 8 { 9 /// <summary> 10 /// 狗类 11 /// </summary> 12 public class Dog:Animals 13 { 14 public Dog(string name ,string color):base(name,color) 15 { 16 17 } 18 public void Bark() 19 { 20 Console.WriteLine("是{0}狗{1},旺旺", base.Color, base.Name); 21 } 22 } 23 }
Dog
---------------------------------------主类Main方法---------------------------------------
1 using JD.entity; 2 using System; 3 using System.Collections.Generic; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace JD 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 //动物 15 List<Animals> listAnimals = new List<Animals>(); 16 17 //添加Cat 18 listAnimals.Add(new Cat("加菲","红色")); 19 listAnimals.Add(new Cat("变色","黄色")); 20 21 //添加Dog 22 Dog d = new Dog("泰迪","黑色"); 23 Dog d1 = new Dog("大黄","黄色"); 24 listAnimals.Add(d); 25 listAnimals.Add(d1); 26 //遍历 27 foreach (var item in listAnimals) 28 { 29 //判断 30 if (item is Dog) 31 { 32 ((Dog)item).Bark(); 33 } 34 if (item is Cat) 35 { 36 ((Cat)item).Bark(); 37 } 38 } 39 } 40 } 41 }
Program
时间: 2024-10-10 00:13:27