目录
一、集合
集合类Collection Class
C#中的数组实现为System.Array类的实例,只是集合类中的一种类型
集合类一般用于处理对象列表,功能大多是通过实现System.Collections名称空间中的接口而获得
集合的功能(包括基本功能)可以通过接口来实现,可以使用基本集合类(System.Array),可以创建定制集合类
System.Collections名称空间中的几个接口提供了基本的集合功能:
IEnumerable可以迭代集合中的项
ICollection(继承于IEnumerable)可以获取集合中项的个数,并能把项复制到一个简单的数组类型中
IList(继承于IEnumerable和ICollection)提供了集合的项列表,允许访问这些项,并提供其他一些与项列表相关的基本功能
IDictionary(继承于IEnumerable和ICollection)类似于IList,但提供了可通过键值(而不是索引)访问的项列表
System.Array类实现了IList、ICollection和IEnumerable,但不支持IList的一些更高级功能,它表示大小固定的项列表
二、使用集合
Systems.Collections名称空间中的类System.Collections.ArrayList也实现了IList、ICollection和IEnumerable接口,但实现方式比System.Array更复杂。
System.Array数组的大小是固定不变的(不能添加或删除元素)
System.Collections.ArrayList类可以用于表示大小可变的项列表
代码参考:
https://media.wiley.com/product_ancillary/85/11190966/DOWNLOAD/Chapter11code.zip
准备好的基类和派生类先写在这里,使用的命名空间都是Animals
基类 Animal.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace Animals
{
/// <summary>
///
/// </summary>
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() => WriteLine($"{name} has been fed.");
}
}
派生类 Cow.cs Chicken.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace Animals
{
public class Cow : Animal
{
public void Milk() => WriteLine($"{name} has been milked.");
public Cow(string newName) : base(newName) { }
}
}
us