ICollection是IEnumerable的加强型接口,它继承自IEnumerable接口,提供了同步处理、赋值及返回内含元素数目的功能,
MSDN解释:
定义所有非泛型集合的大小、枚举器和同步方法。(这里的枚举器来源于IEnumberable,因为ICollection继承于IEnumerable)。
以上就是ICollection的本质。由于很多集合类都直接过间接实现了ICollection接口,所以就有了相应的属性和方法。
下面是ICollection接口的原型。
namespace System.Collections
{
// 摘要:
// 定义所有非泛型集合的大小、枚举器和同步方法。
[ComVisible(true)]
public interface ICollection : IEnumerable
{
// 摘要:
// 获取 System.Collections.ICollection 中包含的元素数。
//
// 返回结果:
// System.Collections.ICollection 中包含的元素数。
int Count { get; }
//
// 摘要:
// 获取一个值,该值指示是否同步对 System.Collections.ICollection 的访问(线程安全)。
//
// 返回结果:
// 如果对 System.Collections.ICollection 的访问是同步的(线程安全),则为 true;否则为 false。
bool IsSynchronized { get; }
//
// 摘要:
// 获取一个可用于同步对 System.Collections.ICollection 的访问的对象。
//
// 返回结果:
// 可用于同步对 System.Collections.ICollection 的访问的对象。
object SyncRoot { get; }
// 摘要:
// 从特定的 System.Array 索引处开始,将 System.Collections.ICollection 的元素复制到一个 System.Array
// 中。
//
// 参数:
// array:
// 作为从 System.Collections.ICollection 复制的元素的目标位置的一维 System.Array。System.Array
// 必须具有从零开始的索引。
//
// index:
// array 中从零开始的索引,将在此处开始复制。
//
// 异常:
// System.ArgumentNullException:
// array 为 null。
//
// System.ArgumentOutOfRangeException:
// index 小于零。
//
// System.ArgumentException:
// array 是多维的。- 或 -源 System.Collections.ICollection 中的元素数目大于从 index 到目标 array
// 末尾之间的可用空间。
//
// System.ArgumentException:
// 源 System.Collections.ICollection 的类型无法自动转换为目标 array 的类型。
void CopyTo(Array array, int index);
}
}
SyncRoot及IsSynchronized属性代表着此Collection是否支持同步处理,当Collection支持同步处理时,就必须于IsSynchronized返回True,并于SyncRoot中返回一个对象引用作为lock时所使用的对象。
MSDN解释:
IsSynchronized :获取一个值,该值指示是否同步对ICollection 的访问(线程安全)。
SyncRoot :获取可用于同步对ICollection 的访问的对象。
下面的程序是简单的ICollection实现范例:
public class MyCollectioin:ICollection
{
private string[] list;
private object root;
public MyCollection()
{
list = new string[3]{"1","3","4"};
}
#region ICollection Members
public bool IsSynchronized
{
get{
return true;
}
}
public int Count
{
get
{
return list.Length;
}
}
public void CopyTo(Array array,int index)
{
list.CopyTo(array,index);
}
public object SyncRoot
{
get
{
return root;
}
}
#endregioin
#region IEnumerable Members
public IEnumerable GetEnumerator()
{
return list.GetEnumerator();
}
#endregion
}
备注:
ICollection 接口是 System.Collections 命名空间中类的基接口。
ICollection 接口扩展 IEnumerable;IDictionary 和 IList 则是扩展 ICollection 的更为专用的接口。 IDictionary 实现是键/值对的集合,如 Hashtable 类。 IList 实现是值的集合,其成员可通过索引访问,如 ArrayList 类。
某些集合(如 Queue 类和 Stack 类)限制对其元素的访问,它们直接实现 ICollection 接口。
如果 IDictionary 接口和 IList 接口都不能满足所需集合的要求,则从 ICollection 接口派生新集合类以提高灵活性。
有关此接口的泛型版本,请参见 System.Collections.Generic.ICollection(Of T)。