非强类型的SortedList如何支持重复键可以参照Pharaoh在2005年就写的blog:《不排序和可以重复key的SortedList》,强类型的SortedList同非强类型的一样可以支持重复键,并不像MSDN上所说的那样,“In either case, a SortedList does not allow duplicate keys.”。
比较非强类型的SortedList,强类型的SortedList需要综合应用C#泛型,接口,继承以及Singleton设计模式来实现,短短几十行代码还是很有点味道的,下面示例是一个允许DateTime键重复,按照DateTime先后顺序排序的一个事件队列的实现:
1
internal
class
CEventListComparer : IComparer
<
DateTime
>
2 {
3 static private CEventListComparer mono;
4 public static CEventListComparer EarlyFirst
5 {
6 get
7 {
8 if (mono == null )
9 mono = new CEventListComparer();
10 return mono;
11 }
12 }
13
14 #region IComparer
15 public int Compare(DateTime x, DateTime y)
16 {
17 if (x == y)
18 return - 1 ;
19 else if (x < y)
20 return - 1 ;
21 else
22 return 1 ;
23 }
24 #endregion
25 }
26
27 internal class CEventList : SortedList<DateTime, IScheduleable>
28 {
29 public CEventList() : base(CEventListComparer.EarlyFirst)
30 {
31 }
32
33 public IScheduleable PopEarlistSchedule(out DateTime newTime)
34 {
35 IScheduleable ish = null;
36 IEnumerator<KeyValuePair<DateTime, IScheduleable>> getFirst = GetEnumerator();
37 getFirst.MoveNext();
38 newTime = getFirst.Current.Key;
39 ish = getFirst.Current.Value;
40 RemoveAt(0);
41 return ish;
42 }
43
44 internal void Schedule(DateTime ScheduledTime, IScheduleable ScheduledCall)
45 {
46 Add(ScheduledTime, ScheduledCall);
47 }
48 }
2 {
3 static private CEventListComparer mono;
4 public static CEventListComparer EarlyFirst
5 {
6 get
7 {
8 if (mono == null )
9 mono = new CEventListComparer();
10 return mono;
11 }
12 }
13
14 #region IComparer
15 public int Compare(DateTime x, DateTime y)
16 {
17 if (x == y)
18 return - 1 ;
19 else if (x < y)
20 return - 1 ;
21 else
22 return 1 ;
23 }
24 #endregion
25 }
26
27 internal class CEventList : SortedList<DateTime, IScheduleable>
28 {
29 public CEventList() : base(CEventListComparer.EarlyFirst)
30 {
31 }
32
33 public IScheduleable PopEarlistSchedule(out DateTime newTime)
34 {
35 IScheduleable ish = null;
36 IEnumerator<KeyValuePair<DateTime, IScheduleable>> getFirst = GetEnumerator();
37 getFirst.MoveNext();
38 newTime = getFirst.Current.Key;
39 ish = getFirst.Current.Value;
40 RemoveAt(0);
41 return ish;
42 }
43
44 internal void Schedule(DateTime ScheduledTime, IScheduleable ScheduledCall)
45 {
46 Add(ScheduledTime, ScheduledCall);
47 }
48 }
上面的事件队列(CEventList)正是我在编写的离散事件仿真程序的核心数据结构,是生产代码哦