2013-03-01 74 views
1

得到一个枚举我有这样的对象:无法从排序列表

class Animation 
    { 
     //[...] 
     private SortedList<int,Frame> frames = new SortedList<int,Frame>(); 
     private IDictionaryEnumerator frameEnumerator = null; 

     //[...] 

     public void someFunction() { 
      frameEnumerator = frames.GetEnumerator(); //throw error 
     } 

     //[...] 

} 

我查MSN的文件有:http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.getenumerator.aspx,它看起来像我的代码是正确的,但VS说:

不能将“System.Collections.Generic.IEnumerator>' 转换为'System.Collections.IDictionaryEnumerator'。

+0

你为什么要获得一个枚举器,而不是通过'foreach'或类似的方法*使用*它? – 2013-03-01 23:18:42

+0

这是因为我想获取当前元素。帧有temporisation,在一个指定的延迟之后,enumeotar将进入下一个。 – 2013-03-01 23:25:49

回答

4

IDictionaryEnumerator类型用于旧的非泛型集合类型。在这种情况下,你有一个强类型集合,它将返回IEnumerater<KeyValuePair<int, Frame>>。使用这种类型,而不是

private IEnumerator<KeyValuePair<int, Frame>> frameEnumerator = null; 

注:SortedList<TKey, TValue>枚举类型确实实现IDictionaryEnumerator接口。如果你真的喜欢那个你可以访问它明确铸造

frameEnumerator = (IDictionaryEnumerator)frames.GetEnumerator(); 

我会尽量避免这条路线。最好使用强类型接口,并避免代码中不必要的强制转换。

+0

谢谢,它的工作:) – 2013-03-01 23:21:10

+0

我必须等待10分钟接受答案...不知道为什么,但我会。 – 2013-03-01 23:21:52

0

尝试投

frameEnumerator = frames.GetEnumerator() as IDictionaryEnumerator; 

之后,请务必检查是否frameEnumerator为null。