using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace 集合{
//动物类
public abstract class Animal
{
protected string name; //动物的名字
public string Name
{
get { return name; }
set { name = value; }
}
public Animal()
{
name="The animal with no name";
}
public Animal(string newName)
{
name=newName;
}
public void Feed() //繁殖后代
{
Console.WriteLine("{0} has been fed.",name);
}
}
//奶牛类
public class Cow : Animal
{
public Cow(string newName): base(newName)
{ }
public void Milk() //产牛奶
{
Console.WriteLine("{0} has been milked.", name);
}
}
//母鸡类
public class Chicken : Animal
{
public Chicken(string newName):base(newName)
{ }
public void LayEgg() //下蛋
{
Console.WriteLine("{0} has laid an egg.", name);
}
}
class Program
{
static void Main(string[] args)
{
//用数组的方法实现
Console.WriteLine("Create an Array type collection of Animal object and use it:");
Animal[] animalArray = new Animal[2];
Cow myCow1 = new Cow("Deirdre");
animalArray[0] = myCow1;
animalArray[1] = new Chicken("Ken");
foreach (Animal myAnimal in animalArray )
{
Console.WriteLine("New {0} object added to Array collection,Name={1}", myAnimal.ToString(), myAnimal.Name);
}
Console.WriteLine("Array collection contains {0} objects.",animalArray .Length );
animalArray[0].Feed();
((Chicken)animalArray[1]).LayEgg();
Console.WriteLine();
//用集合的方法实现
Console.WriteLine("Create an ArrayList type collection of Animal objects and use it;");
ArrayList animalArrayList = new ArrayList();
Cow myCow2 = new Cow("HayLey");
animalArrayList.Add(myCow2);
animalArrayList.Add(new Chicken("Roy"));
foreach (Animal myAnimal in animalArrayList)
{
Console.WriteLine("New {0} object added to ArrayList collection,Name={1}", myAnimal.ToString(), myAnimal.Name);
}
Console.WriteLine("ArrayList collection contains {0} objects.", animalArrayList.Count);
((Animal)animalArrayList[0]).Feed();
((Chicken)animalArrayList[1]).LayEgg();
Console.WriteLine();
}
}
}
Animal[] animalArray = new Aimal[2];
ArrayList animalArrayList = new ArrayList();
Cow myCow2 = new Cow("Hayley");
anmialArrayList.Add(myCow2);
anmialArrayList.Add(new Chicken("Roy"));
foreach (Animal myAnimal in animalArrayList)
{
Console.WriteLine("New {0} object added to ArrayList collection,Name = {1}",myAnimal.Tostring(),myAnimal.Name);
}
((Animal)animalArrayList[0]).Feed(); ((Chichen)animalArrayList[1]).LayEgg();
animalArrayList.RemoveAt(0); animalArrayList.Remove(myCow2);
animalArrayList.AddRange(animalArray);
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有