接口 | 用途 |
ICollection<T> | 泛型集合的基接口 |
IEnumerator<T> IEnumerable<T> | 使用foreach语句枚举整个集合 |
ICollection<T> | 被所有集合实现以提供CopyTo()方法,Count,IsSynchronized和SyncRoot属性 |
IComparer<T> IComparable<T> | 对比集合中的两个对象,使得集合可以被排序 |
IList<T> | 象数组一样使用索引访问集合 |
IDictionary<K,V> | 在基于键/值的集合中使用,如Dictionary |
using System;
using System.Collections; //译者注:这句原文没有,必须添加
using System.Collections.Generic;
using System.Text;
namespace Enumerable
{
public class ListBoxTest : IEnumerable<string>
{
private string[] strings;
private int ctr = 0;
//Enumerable类可以返回一个枚举器
public IEnumerator<string> GetEnumerator()
{
foreach (string s in strings)
yield return s;
}
/*译者注:泛型IEnumerable的定义为
*public interface IEnumerable<T> : IEnumerable
* 也就是说,在实现泛型版IEnumerable的同时还必须同时实现
* 非泛型版的IEnumerable接口,原文代码并没有这个内容,下面的三行
* 代码是我添加进去的以使得代码可以直接拷贝并运行*/
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
//使用字符串数组来初始化ListBox
public ListBoxTest(params string[] initialStrings)
{
//为strings分配空间
strings = new string[8];
//拷贝从构造方法传递进来的字符串数组
foreach (string s in initialStrings)
{
strings[ctr++] = s;
}
}
//在ListBox未尾添加一个字符串
public void Add(string theString)
{
strings[ctr] = theString;
ctr++;
}
//允许象数组一样访问,其实就是索引器,如果对索引器有不明白的请访问:
//http://www.enet.com.cn/eschool/video/c/20.shtml
public string this[int index]
{
get
{
if (index < 0 || index >= strings.Length)
{
//处理错误的索引
//译者注:原文这里没加代码,我加了一个异常下去
throw new ArgumentOutOfRangeException("索引", "索引超出范围");
}
return strings[index];
}
set
{
strings[index] = value;
}
}
//获得拥有字符串的数量
public int GetNumEneries()
{
return ctr;
}
}
public class Tester
{
static void Main()
{
//创建一个新的ListBox并初始化
ListBoxTest lbt = new ListBoxTest("Hello", "World");
//添加一些字符串
lbt.Add("Who");
lbt.Add("Is");
lbt.Add("John");
lbt.Add("Galt");
//访问测试
string subst = "Universe";
lbt[1] = subst;
//列出所有字符串
foreach (string s in lbt)
{
Console.WriteLine("Value: {0}", s);
}
}
}
}