是否有转换的IEnumerator IEnumerable的到一个内置的方式 [英] Is there a built-in way to convert IEnumerator to IEnumerable

查看:136
本文介绍了是否有转换的IEnumerator IEnumerable的到一个内置的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有转换一个内置的方式的IEnumerator< T> 的IEnumerable< T>

Is there a built-in way to convert IEnumerator<T> to IEnumerable<T>?

推荐答案

您可以使用这将还挺工作下面。

You could use the following which will kinda work.

public class FakeEnumerable<T> : IEnumerable<T> {
  private IEnumerator<T> m_enumerator;
  public FakeEnumerable(IEnumerator<T> e) {
    m_enumerator = e;
  }
  public IEnumerator<T> GetEnumerator() { 
    return m_enumerator;
  }
  // Rest omitted 
}

这将得到你陷入困境虽然当人们期望连续调用的GetEnumerator以对的同一个返回不同的统计员。但是,如果它是一个一次仅在非常受限情况下使用,这可以解除你。

This will get you into trouble though when people expect successive calls to GetEnumerator to return different enumerators vs. the same one. But if it's a one time only use in a very constrained scenario, this could unblock you.

我不建议,虽然你尝试这样做这一点,因为我觉得最终还是会回来困扰你。

I do suggest though you try and not do this because I think eventually it will come back to haunt you.

一个更安全的选择是沿着乔纳森建议的方式。你可以花费的枚举和创建一个列表< T> 剩余的项目。

A safer option is along the lines Jonathan suggested. You can expend the enumerator and create a List<T> of the remaining items.

public static List<T> SaveRest<T>(this IEnumerator<T> e) {
  var list = new List<T>();
  while ( e.MoveNext() ) {
    list.Add(e.Current);
  }
  return list;
}

这篇关于是否有转换的IEnumerator IEnumerable的到一个内置的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆