首页 > 代码库 > (深入.Net平台和C#编程)第六章.简答题3.20170410
(深入.Net平台和C#编程)第六章.简答题3.20170410
---------------------------------------父类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 }
---------------------------------------子类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 }
---------------------------------------子类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 }
---------------------------------------主类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 }
(深入.Net平台和C#编程)第六章.简答题3.20170410
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。