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

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

问题描述

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

解决方案

foreach not 需要 IEnumerable,这与流行的看法相反.它所需要的只是一个方法 GetEnumerator,该方法返回具有方法 MoveNext 和具有适当签名的 get-property Current 的任何对象.>

/但是,就您而言,您运气不佳.但是,您可以简单地包装您的对象以使其可枚举:

class EnumerableWrapper {私有只读 TheObjectType obj;公共 EnumerableWrapper(TheObjectType obj) {this.obj = obj;}公共 IEnumerator获取枚举器(){返回 obj.TheMethodReturningTheIEnumerator();}}//像这样调用:foreach (var xyz in new EnumerableWrapper(yourObj))……;

/以下方法由几个人提出,如果该方法返回 IEnumerator不起作用:

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

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 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.

/EDIT: 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))
    …;

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

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

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

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