小议CollectionBase类 C#集合类

今天看书时,对基于CollectionBase类的自定义集合有点迷惑,查了下MSDN,自己做了一些小测试,得出一些心得。
1.IEnumerator,功能:支持对非泛型集合的简单迭代,这个接口有两个方法(MoveNext,Reset),一个属性(Current)。为foreach语句提供了迭代的基础,参阅《C#入门经典》,foreach首先调用IEnumerator接口的MoveNext,判断索引元素是否为空,不为空就取出Current属性保存的值,循环此过程直到moveNext为假。MSDN有一个模拟IEnumerator的例子,看后理解更加清楚了。
2.IEnumerable,功能:公开枚举数,该枚举数支持在非泛型集合上进行简单迭代,这个接口是很多接口的基接口,它有一个方法IEnumerator GetEnumerator(),这个方法为foreach语句返回一个以供迭代的IEnumerator接口对象,换句话说,foreach语句会首先调用这个接口的方法得到一个IEnumerator的实例,再调用IEnumerator的方法以完成迭代。所以要编写自定义类的foreach循环就要实现这个接口,经测试发现,即使不继承这个接口,而去实现接口的方法也是可以完成迭代的,这进一步说明foreach语句不检查类是否支持IEnumerable接口,而是直接去调用类里面的IEnumerator GetEnumerator()方法。
3,IColletion接口,功能:定义所有非泛型集合的大小、枚举数和同步方法,这个接口继承自IEnumerable接口,增加了一些新的功能,主要是实现记录集合中元素个数(Count属性),将集合中元素复制到一个指定数组中。
4.IList接口,功能:表示可按照索引单独访问的对象的非泛型集合,这个接口继承自IColletion接口和IEnumerable接口。还新增了很多功能。如提供对集合中元素的索引(object this[int index]),添加,插入,删除(按值或按索引删除),清空 集合中的元素(Add,Insert,Remove,RemoveAt,clear),查询某个元素的索引(IndextOf),判断某个元素是否在集合中(contain),判断集合是否为固定大小(IsFixedSize),集合中元素是否为只读(IsReadOnly)等功能。

5.BaseCollection类是一个抽象类,不能被实例化,只能被继承。功能:为强类型集合提供 abstract 基类。它继承了三个接口:IListt, ICollection,IEnumerable,它直接实现了IEnumerable接口的方法,直接实现了ICollection接口的count属性,显示实现了Icollection接口的其它三个方法。显示实现了IList的所有方法。由于IList接口是从IColletion和IEnumerable接口继承而来的所以会看到重复的方法,如count属性和List.count属性,clear方法和List.Clear方法,removeAt方法和List.RemoveAt方法,GetEnumerator方法和List.GetEnumerator方法(可能在MSDN上不存在重复,但以编译器为准),我的猜想是重复的直接实现的接口其实是调用了IList中显式实现的方法。

6.对CollectionBase类中List接口实例的猜想,下面是我写的一段代码,模拟CollectionBase类List接口实例的实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ContainObject
{
interface ISaySomething //模拟Ilist接口
{
void SaySomething();
void Increase();

}

abstract class Test:ISaySomething //模拟CollectionBase类
{
private ISaySomething list = new StoreValue();
protected ISaySomething List //模拟List属性
{
get { return list; }
}

void ISaySomething.SaySomething() //模拟collectionBase类中显式接口的实现,
{ //实际上调用了list中的方法
list.SaySomething();
}
void ISaySomething.Increase() //同上
{
list.Increase();
}
private class StoreValue : ISaySomething //真正实现IList接口的内部类
{
private int[] values = { 5, 6 };

public void SaySomething()
{
Console.WriteLine("value is {0} and {1}", values[0], values[1]);
}
public void Increase()
{
values[0]++;
values[1]++;
}
}
}
class MyClass: Test //模拟继承自collectionBase的自定义集合
{
public void Say()
{
List.SaySomething();
}
public void Add()
{
List.Increase();
}

}
class Program
{
static void Main(string[] args)
{
MyClass myclass = new MyClass();
myclass.Add();
myclass.Say();
Console.ReadKey();
}
}
}
由于collectionBase显示实现接口Ilist类,它又是抽象的不能产生实例转换为接口,所以这些显示的接口成员将变为私有的,实例不可访问它,只能通过它提供的list属性间接访问


  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值