祖宗:IEnumerable
此接口只有一个方法 GetEnumerator();
是FrameWork为了实现迭代器模式设计的接口。所有继承了IEnumerable的类,要使用foreach迭代器时,就需要使用该方法。因此也只有实现了该接口的类才可以使用foreach。
ICollection继承自IEnumerable,IList继承自ICollection
这两个接口都是为了给集合提供一些公用的方法。只是分了两个层次,IList比ICollection多几个方法,增加,移除成员。可以简单理解为:ICollection主要针对静态集合;IList主要针对动态集合。
IList,ICollection,IEnumerable 在命名空间System.Collections中。
IList<T>,ICollection<T>,IEnumerable<T> 在System.Collections.Generic 命名空间中。
IList<T>,ICollection<T>,IEnumerable<T> 是2.0引入泛型以后新增的。主要是提高重用性与类型安全。
IEnumerable<T>继承自IEnumerable
ICollection<T>继承自IEnumerable<T>
IList<T>继承自ICollection<T>
因此可以完全使用泛型接口,而放弃使用ICollection和IList。泛型接口提供了更好的类型安全和编译时的检验。
补充:
IEnumerable<T>和IEnumerable都只有一个方法。ICollection<T>和ICollection的结构是不一样的。ICollection<T>比ICollection多几个方法。它包含了几个IList中的几个方法。也许是对以前的改进。
《转自》Valsun's Blog
http://blog.sina.com.cn/s/blog_586b6c05010096tl.html
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/shaoyupeng/archive/2008/12/22/3581205.aspx
实现ICollection例子
1
using System;2
using System.Collections;3

4
namespace Relaction.Collections5
{6
/// <summary>7
/// 8
/// </summary>9
public class MyCollections:ICollection10
{11
private string[] _list;12
private object _root = new object();13
public MyCollections()14
{15
_list = new string[3]{"1","2","3"};16
}17
#region ICollection 成员18

19
public bool IsSynchronized20
{21
get22
{23
return true;24
}25
}26

27
public int Count28
{29
get30
{31
return _list.Length;32
}33
}34

35
public void CopyTo(Array array, int index)36
{37
_list.CopyTo(array,index);38
}39

40
public object SyncRoot41
{42
get43
{44
return _root;45
}46
}47

48
#endregion49

50
#region IEnumerable 成员51

52
public IEnumerator GetEnumerator()53
{54
return _list.GetEnumerator();55
}56

57
#endregion58
}59
}60

1
private void button7_Click(object sender, System.EventArgs e)2
{3
Relaction.Collections.MyCollections c = new Relaction.Collections.MyCollections();4
foreach(string s in c)5
{6
label1.Text += s.ToString();7
}8
}


浙公网安备 33010602011771号