什么是一个IEnumerator转换为一个通用的IEnumerator的最佳方式? [英] What is the best way to convert an IEnumerator to a generic IEnumerator?

查看:401
本文介绍了什么是一个IEnumerator转换为一个通用的IEnumerator的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写在C#.NET 3.5的自定义ConfigurationHandler定制ConfigurationElementCollection中,我想揭露的IEnumerator作为一个通用的IEnumerator。

I am writing a custom ConfigurationElementCollection for a custom ConfigurationHandler in C#.NET 3.5 and I am wanting to expose the IEnumerator as a generic IEnumerator.

会是什么实现这一目标最好的方式。

What would be the best way to achieve this?

我目前使用的代码:


public new IEnumerator<GenericObject> GetEnumerator()
{
  var list = new List();
  var baseEnum = base.GetEnumerator();
  while(baseEnum.MoveNext())
  {
    var obj = baseEnum.Current as GenericObject;
    if (obj != null)
      list.Add(obj);
  }
  return list.GetEnumerator();
}



干杯

Cheers

推荐答案

我不相信有在框架中任何东西,但你可以很容易地写一个:

I don't believe there's anything in the framework, but you could easily write one:

IEnumerator<T> Cast<T>(IEnumerator iterator)
{
    while (iterator.MoveNext())
    {
        yield return (T) iterator.Current;
    }
}

在您的情况,但是,它更容易 - 现有的类已经实现了的IEnumerable ,这样你就可以使用铸造方法在LINQ:

In your case, however, it's easier - the existing class already implements IEnumerable, so you can use the Cast method in LINQ:

public new IEnumerator<T> GetEnumerator()
{
    return this.Cast<T>().GetEnumerator();
}



另外,客户可以只叫演员LT; T> 自己:)

还有 OfType<> ,这是演员LT; T> ,但简单地忽略那些合适类型的不值。我个人使用演员LT;> 往往 OfType<> ;如果所有的值是真正的意味着的是合适的类型,演员LT;> 更好IMO,因为它会爆炸失败(有一个例外),而不是只是默默地忽略的价值 - 这提醒您的问题

There's also OfType<>, which is like Cast<T>, but will simply omit values that aren't of the appropriate type. Personally I use Cast<> more often than OfType<>; if all the values are really meant to be of the appropriate type, Cast<> is better IMO as it will fail explosively (with an exception) rather than just silently omitting the value - this alerts you to the problem.

至于的报告铸造 StackOverflowException OfType 不这样做 - 这是很难知道这是为什么,没有一个例子证明它

As for the reports of Cast throwing a StackOverflowException and OfType not doing so - it's hard to know why that is without an example demonstrating it.

这篇关于什么是一个IEnumerator转换为一个通用的IEnumerator的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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