为了能够使用一个类型的实例作为IEnumerable<T>
,类型必须实现IEnumerable<T>
。表明您想在声明的类名称后添加: IEnumerable<T>
做到这一点:
public class Container<T> : IEnumerable<T>
// ...
当你这样做,你会得到编译器错误抱怨说,你还没有实现所有需要的成员。你的IDE应该能够为他们自动生成存根,但是这是你必须做的:
public class Container<T> : IEnumerable<T>
{
// forward the non-generic version to the generic version
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
// implement GetEnumerator from the generic interface
public IEnumerator<T> GetEnumerator()
{
throw new NotImplementedException();
}
}
现在,实行最常见的方式自己IEnumerable<T>
是裹在内置一个,例如一个List<T>
或一个数组。如果这就是你正在做的事情,你可以将GetEnumerator()
调用转发给内部实例并完成。
如果你想做一些更复杂的事情,你可以例如使用yield return
结构构建您的迭代协议:
public IEnumerator<T> GetEnumerator()
{
// do some work
// then return the first element:
yield return default(T); // yeah, you probably have an actual value
// do some more work
// return another value:
yield return default(T);
// if you want to abort the iteration prematurely
// e.g. based on some condition
// you can
yield break;
}
您的问题没有意义。什么是GetStuff?这里是否得到'string'数据?你不能将一个类转换成IEnumerable类,你可以实现它。 –
@PatrickHofman,填充容器类的方法。 – KyloRen
如何?什么?什么时候? –