[英]Implementing IEnumerable<interface> Generic
我是c#的新手并且已经阅读了关于这个话题的主题,但我仍然遇到了麻烦。 在此先感谢您的建议和意见。
从顶层开始,我正在实现一个包含方法的接口
IEnumerable<Iinterfacetype> methodname(inputtype input)
在这种情况下,似乎我应该返回IEnumerable<Iinterfacetype>
类型的对象。 为了做到这一点,我试图创建一个实现IEnumerable<Iinterfacetype>
的新脚本。 到目前为止,我的脚本看起来像这样:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace Project3.SimulatedTools.DBImplementations
{
class Enumerable : IEnumerable<interfacetype>
{
List<interfacetype> mylist = new List<interfacetype>();
public IEnumerator<interfacetype> GetEnumerator()
{
return mylist.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
我有另一个名为interfacetype.cs的脚本,它实现了Iinterfacetype。
在原来的顶级,我已经设置了这样:
public IEnumerable<Iinterfacetype> methodname(inputtype input)
{
Enumberable<interfacetype> tempnamehere = new Enumerable();
return(tempnamehere);
}
但是,我一直收到错误:
无法将类型“
Project3.SimulatedTools.DBImplementations.Enumerable
”隐式转换为System.Collections.Generic.IEnumerable<Iinterfacetype>
'。 存在显式转换(您是否错过了演员?)
我该如何解释这个错误? 我是否正确设置了IEnumerable<interfacetype>
的实现? 当interfacetype实现Iinterfacetype时,为什么我不能返回类型IEnumerable<interfacetype>
?
编辑:我的顶级现在看起来像这样,我调整了我的类Enumerable实现IEnumerable而不是更改所有引用。 我不再遇到任何编译错误,但我仍然不明白原始问题是什么,并且尚未将其设置为运行。
public IEnumerable<Iinterfacetype> methodname(inputtype input)
{
Enumberable tempnamehere = new Enumerable();
return(tempnamehere);
}
此外,我是否有必要使用interfacetype:Iinterfacetype,因为我现在已经设置了它? 看起来我从来没有真正使用interfacetype,在这种情况下,它将是无关紧要的。 如果是这样,为什么会这样(我不必实现它)?
让我们看一下IEnumerable<T>
:
公开枚举器,它支持对指定类型的集合进行简单迭代
基本上,任何实现IEnumerable
类型都允许我们迭代给定的集合。
.NET Framework中有一些实现接口的类型:
List<T>
, Dictionary<TKey, TValue>
等
您可以使用BCL(基类库)提供的类型,而只是使用实现它的对象,而不是自己实现IEnumerable<T>
。 在您的情况下, List<interfacetype>
就足够了:
public IEnumerable<Iinterfacetype> methodname(inputtype input)
{
return new List<interfacetype>();
}
你真的永远不会创建一个“新的可枚举”,而是你创造了一些暗示IEnumerable的东西。 最明显的例子是:
var l = new List<string>();
这实现了IEnumerable<string>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.