您的位置:首页 > 编程语言 > C#

C#基础:集合

2016-03-25 17:23 274 查看
C#中的数组实现为 System.Array 类的实例,它们只是集合类(Collection Classes)中的一种类型。集合类一般用于处理对象列表,其功能比简单数组要多,功能大多是通过实现 System.Collections 名称空间中的接口而获得的,因此集合的语法已经标准化了。这个名称空间还包含其他一些有趣的东西,例如,以与 System.Array 不同的方式实现这些接口的类。
集合的功能(包括基本功能,例如[index]语法访问集合中的项)可以通过接口来实现,该接口不仅没有限制我们使用基本集合类,例如 System.Array,相反,我们还可以创建自己的定制集合类。这些集合可以专用于要枚举的对象(即要从中建立集合的对象)。这么做的一个优点是定制的集合类可以是强类型化的。也就是说,从集合中提取项时,不需要把它们转换为正确的类型。另一个优点是提供专用的方法,例如,可以提供获得项子集的快捷方法,在扑克牌示例中,可以添加一个方法,来获得特定花色中的所有 Card 项。

System.Collections 名称空间中的几个接口提供了基本的组合功能:
a、 IEnumerable 可以迭代集合中的项。
b、 ICollection(继承于 IEnumerable)可以获取集合中项的个数,并能把项复制到一个简单的数
组类型中。
c、 IList(继承于 IEnumerable 和 ICollection)提供了集合的项列表,允许访问这些项,并提供其
他一些与项列表相关的基本功能。
d、 IDictionary(继承于 IEnumerable 和 ICollection)类似于 IList,但提供了可通过键值(而不是索
引)访问的项列表。
System.Array 类实现 IList、 ICollection 和 IEnumerable,但不支持 IList 的一些更高级的功能,它
表示大小固定的项列表。

自定义集合:
Animals.cs :
using System.Collections; // 集合类
namespace 自定义集合
{
public class Animals : CollectionBase
{
// Add 和 Remove 实现为强类型化的方法
public void Add(Animals newAnimal)
{
List.Add(newAnimal);
}
public void Remove(Animals oldAnimal)
{
List.Remove(oldAnimal);
}
public Animals(){ }
}
}
Program.cs :
static void Main(string[] args)
{
Console.WriteLine("Using custom collection class Animals");
Animals animalCollection = new Animals();
animalCollection.Add(new Cow("Sarah")); // Cow类这里并没有实现
}

【索引符】
索引符(indexer)是一种特殊类型的属性,可以添加到类中。以提供类似于数组的访问
以上述代码为例

Animals.cs :
using System.Collections; // 集合类
namespace 自定义集合
{
public class Animals : CollectionBase
{
public Animal this[int animalIndex]
{
get{
return (Animal) List[animalIndex];
}
set{
List[animalIndex] = value;
}
}
// Add 和 Remove 实现为强类型化的方法
public void Add(Animals newAnimal)
{
List.Add(newAnimal);
}
public void Remove(Animals oldAnimal)
{
List.Remove(oldAnimal);
}
public Animals(){ }
}
}
static void Main(string[] args)
{
Animals animalCollection = new Animals();
animalCollection.Add(new Cow("Jack"));
animalCollection.Add(new Chicken("Vera"));
foreach (Animal myAnimal in animalCollection)
{
myAnimal.Feed();
}
Console.ReadKey();
}

【迭代器】
using System.Collections;
namespace 迭代器的使用{
class Program{
public static IEnumerable SimpleList(){
yield return "string 1";
yield return "string 2";
// yield break; 终止迭代器的执行
yield return "string 3";
}

static void Main(string[] args){
foreach (var item in SimpleList()){
Console.WriteLine(item);
}
}}}

【对象比较的接口】
IComparable 和 IComparer 接口是.NET Framework 中比较对象的标准方式。这两个接口之间的
差别如下:
* IComparable 在要比较的对象的类中实现,可以比较该对象和另一个对象。
* IComparer 在一个单独的类中实现,可以比较任意两个对象。





【使用IComparable和IComparer接口对集合排序】
例如ArrayList的sort()方法,不带参数时,代表使用默认的排序参数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: