我有这个对象:

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”。

最佳答案

IDictionaryEnumerator类型用于较旧的非通用集合类型。在这种情况下,您将拥有一个强类型集合,它将返回IEnumerater<KeyValuePair<int, Frame>>。请改用该类型

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


注意:SortedList<TKey, TValue>的枚举器类型确实实现了IDictionaryEnumerator接口。如果您真的喜欢那个,可以通过显式强制转换访问它

frameEnumerator = (IDictionaryEnumerator)frames.GetEnumerator();


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

09-04 22:09