2013-03-01 76 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。