工作中点滴记录

永远保持学徒心态

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 

System.Collections 命名空间的一个类System.Collections.ArrayList实现了IList、Icollection、IEnumerable接口,但实现的方式比System.Array复杂。
数组的大小是固定的(不能增加或者删除元素)
ArrayLIst可以用于表示大小可变的项目列表;
下面用代码演示此结果
代码
1 ///  
2 /// 抽象类
3 ///  
4   public abstract class Animal
5 {
6 private string name;
7 public string Name
8 {
9 get { return name; }
10 set { name = value; }
11 }
12 public Animal()
13 {
14 Name = "the Animal with no name";
15 }
16 public Animal(string newName)
17 {
18 Name = newName;
19 }
20 public void Feed()
21 {
22 Console.WriteLine("{0} has been fed", name);
23 }
24 }
代码
1 ///  
2 /// 派生类
3 ///
4   public class Cow : Animal
5 {
6 public void Milk()
7 {
8 Console.WriteLine("{0} has been milked",Name);
9 }
10 public Cow(string newName)
11 : base(newName)
12 {
13 }
14 }
15 ///
16 /// 派生类
17 ///
18   public class Chicken : Animal
19 {
20 public void LayEgg()
21 {
22 Console.WriteLine("{0} has laid an egg", Name);
23 }
24 public Chicken(string newName)
25 : base(newName)
26 {
27 }
28 }
 
 实现方式:
代码
static void Main(string[] args)
{
Console.WriteLine(
"Create an Array type collection of Animal objects and use it:");
Animal[] animalArray
= new Animal[2];
animalArray[
0] = new Cow("Deirdre");
animalArray[
1] = new Chicken("Ken");
foreach (Animal myAni in animalArray)
{
Console.WriteLine(
"New {0} object added to Array collection, Name= {1}", myAni.ToString(), myAni.Name);
}
animalArray[
0].Feed();
((Cow)animalArray[
0]).Milk();
animalArray[
1].Feed();
((Chicken)animalArray[
1]).LayEgg();

Console.WriteLine(
"Create an ArrayList type collection of Animal objects and use it:");
ArrayList list
= new ArrayList();
list.Add(
new Cow("HayLey"));
list.Add(
new Chicken("Roy"));
foreach (Animal item in list)
{
Console.WriteLine(
"New {0} object added to ArrayList collection ,Name = {1} ", item.ToString(), item.Name);
}
Console.WriteLine(
"ArrayList collection contains {0} objects.", list.Count);
((Animal)list[
0]).Feed();
((Cow)list[
0]).Milk();
((Animal)list[
1]).Feed();
((Chicken)list[
1]).LayEgg();

list.RemoveAt(
0);
((Animal)list[
0]).Feed();
((Chicken)list[
0]).LayEgg();
list.AddRange(animalArray);
Cow c
= new Cow("small cow");
list.Add(c);
c.Name
= "Big cow";
((Cow)list[
3]).Milk();
}
posted on 2010-12-16 11:24  梦里故乡  阅读(238)  评论(1编辑  收藏  举报