实现IEnumerable时遇到麻烦我正在尝试编写自己的(简单的)List实现。使用System.Collections.Generic;使用System.Linq;使用系统文本;namespaceprovaIEnum{classMyList:IEnumerable{privateT[]_array;公共int计数{得到;私有集;}publicMyList(){/*...*/}publicvoidAdd(Telement){/*...*/}//...publicIEnumeratorGetEnumerator(){for(inti=0;i<计数;i++)yieldreturn_array[i];我收到有关GetEnumerator的错误消息:“provaIEnum.Lista”未实现接口成员“System.Collections.IEnumerable.GetEnumerator()”。“provaIEnum.Lista.GetEnumerator()”无法实现“System.Collections.IEnumerable.GetEnumerator()”,因为它没有匹配的返回类型“System.Collections.IEnumerator”。我不确定我是否理解VS试图告诉我的内容,而且我不知道如何修复它。感谢您的宝贵时间由于IEnumerable实现了IEnumerable,因此您需要在具有非泛型版本的GetEnumerator方法的类中实现此接口。为避免冲突,您可以显式实现它:IEnumeratorIEnumerable.GetEnumerator(){//调用方法的通用版本returnthis.GetEnumerator();}publicIEnumeratorGetEnumerator(){for(inti=0;ipleaseReadtheerrormessagecarefully;它告诉你到底想做什么。你没有实现System.Collections.IEnumerable.GetEnumerator。当你实现通用IEnumerable,您还必须实现System.Collections.IEnumerable的GetEnumerator。执行此操作的标准方法是:publicIEnumeratorGetEnumerator(){whatever}System.Collections.IEnumerator您还需要实现非泛型GetEnumerator方法:IEnumeratorIEnumerable.GetEnumerator(){returnGetEnumerator();}由于IEnumerable接口扩展了IEnumerable,因此您必须实现在两者上声明的方法。添加以下方法:IEnumeratorIEnumerable。GetEnumerator(){returnthis.GetEnumerator();}您必须实现两个GetEnumerator()重载。一个来自IEnumerable并返回IEnumerator。另一个来自IEnumerable并返回IEnumerator。覆盖应如下所示:IEnumeratorIEnumerable.GetEnumerator()这是因为IEnumerable实现了IEnumerable。由于您的类MyList继承了IEnumerable而IEnumerable继承了非泛型IEnumerable,因此您需要实现两个方法:IEnumeratorIEnumerable.GetEnumerator(){thrownewNotImplementedException();}System.Collections.IEnumeratorSystem.Collections.IEnumerable.GetEnumerator(){thrownewNotImplementedException();一个简单的方法是在声明类时:classMyList:IEnumerable右键单击??IEnumerable文本并从上下文菜单中选择ImplementInterface>ImplementInterfaceExplicit。我有一个类似的问题,虽然我也实现了IEnumerable和IEnumerable。我使用自定义类型(Person类)而不是泛型类型T。我的原因是名称空间未包含在文件顶部。使用System.Collections添加命名空间后;它对我来说很好用。以上就是C#学习教程的全部内容:实现IEnumerable的烦恼。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
