目录
第十一章 集合、比较和转换
第十一章 集合、比较和转换
- 集合:可以使用集合来维护数组,控制对它们对象的访问、搜索和排序等。
- 比较:在处理对象时常用到它们。这对于集合尤其重要,因为这是排序的实现方式。
- 转换:定制类型转换,以满足自己的需要。
11.1集合
数组一旦建好,其大小是固定的。
集合类一般用于处理对象列表,其功能比简单数组要多,功能大多是通过实现System.Collections名称空间中的接口而获得的,因此集合的语法已经标准化了。
集合的功能(包括基本功能,例如,用【index】语法访问集合中的项)可以通过接口来实现。
System.Collections名称空间中的几个接口提供了基本的集合功能:
- IEnumerable——可以迭代集合中的项(单词解释:enumerable-adj. 可列举的;可点数的)
- ICollection——(继承于IEnumerable)可以获取集合中项的个数,并能把项复制到一个简单的数组类型。
- IList——(继承于IEnumerable和ICollection)提供了集合的项列表,允许访问这些项,并提供其他一些与列表相关的基本功能。
- IDictionary——(继承于IEnumerable 和IColleciton)类似于IList,但提供了可通过键值(而不是索引)访问的项列表。
11.1.1 使用集合
1-->创建三个类,Animal,Cow,Chicken,Cow:Animal,Chicken:Animal;
Animal.cs
namespace Ch11Ex01
{
//Define a abstract class Animal
public abstract class Animal
{
//protected ,to access the domain in the class(Animal) or in a class extends the class(Animal)
protected string name;
public string Name //attention please,the capital of Name
{
get
{
return name;
}
set
{
name = value;
}
}
//To define a method
public Animal()
{
name = "The animal with no name";
}
//To define a method with parameter
public Animal(string newName)
{
name = newName;
}
//To define a method without returned value
public void Feed()
{
Console.WriteLine("{0} has been fed.",name);
}
}
}
Cow.cs
namespace Ch11Ex01
{
//Define a class(Cow)to extend Animal
class Cow : Animal
{
//Define a method to describe animals' actions
public void Milk()
{
Console.WriteLine("{0} has been milked.",name);
}
//base关键字指定.NET实例化过程使用基类中具有指定参数的构造函数。
public Cow(string newName)
: base(newName)