类是否需要实现IEnumerable使用Foreach源 [英] Does Class need to implement IEnumerable to use Foreach

查看:148
本文介绍了类是否需要实现IEnumerable使用Foreach源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在C#中,我有我一些其他的DLL使用类。它没有实现IEnumerable,但有2种方法是传递回的IEnumerator。有没有一种方法,我可以使用这些foreach循环。我使用的是密封类。

This is in C#, I have a class that I am using from some else's DLL. It does not implement IEnumerable but has 2 methods that pass back a IEnumerator. Is there a way I can use a foreach loop on these. The class I am using is sealed.

推荐答案

的foreach 做的的要求的IEnumerable ,出乎人们意料。它所需要的是一个方法的GetEnumerator 返回具有方法的MoveNext 和获取属性<$ C的任何对象$ C>当前与适当的签名

foreach does not require IEnumerable, contrary to popular belief. All it requires is a method GetEnumerator that returns any object that has the method MoveNext and the get-property Current with the appropriate signatures.

/编辑:在你的情况,但是,你的运气了。你可以平凡包装你的对象,但是,使其枚举:

/ In your case, however, you're out of luck. You can trivially wrap your object, however, to make it enumerable:

class EnumerableWrapper {
    private readonly TheObjectType obj;

    public EnumerableWrapper(TheObjectType obj) {
        this.obj = obj;
    }

    public IEnumerator<YourType> GetEnumerator() {
        return obj.TheMethodReturningTheIEnumerator();
    }
}

// Called like this:

foreach (var xyz in new EnumerableWrapper(yourObj))
    …;



/编辑:下面的方法,由几个人提出,确实的的工作,如果该方法返回一个的IEnumerator

/ The following method, proposed by several people, does not work if the method returns an IEnumerator:

foreach (var yz in yourObj.MethodA())
    …;

这篇关于类是否需要实现IEnumerable使用Foreach源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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