《C#入门经典(第5版)》系列(11):集合、比较和转换

1、集合

  1、System.Array数组的大小是固定的,不能增加或删除元素;另外,数组是引用类型。

  2、我们可以从一个类中派生自己的集合,例如System.Collections.CollectionBase类,这个抽象类提供了集合类的许多实现方式。这是推荐使用的方式。CollectionBase类有接口IEnumerable、ICollection和IList,但只提供了一些需要的实现代码,特别是IList的Clear()和RemoveAt()方法,以及ICollection的Count属性。如果要使用提供的功能,就需要自己执行其他代码。

  CollectionBase提供了两个受保护的属性,他们可以访问存储的对象本身。我们可以使用List和InnerList,List可以通过IList接口访问项,InnerList则是用于存储项的ArrayList对象。例如:

View Code
 1 public abstract class Animal : CollectionBase
 2 {
 3         public void Add(Animal newAnimal)
 4         {
 5             List.Add(newAnimal);
 6         }
 7         public void Remove(Animal oldAnimal)
 8         {
 9             List.Remove(oldAnimal);
10             
11         }
12 }

  其中,Add()和Remove()方法实现为强类型化的方法,使用IList接口中用于访问项的标准Add()方法。

  3、索引符(indexer),是一种特殊类型的属性,可以把它添加到一个类中,以提供类似于数组的访问。例如:

View Code
 1 public class Animals
 2     {
 3         public Animal this[int animalIndex]
 4         {
 5             get
 6             {
 7                 return (Animal)List[animalIndex];
 8             }
 9             set
10             {
11                 List[animalIndex] = value;
12             }
13         }
14     }

  this关键字和方括号中的参数一起使用,看起来类似于其他属性。在访问索引符时,将使用对象名,后跟放在方括号中的索引参数(例如MyAnimals[0])。

未完待续。。。

原文地址:https://www.cnblogs.com/GISerYang/p/3046028.html