为什么我们需要IEnumerator和IEnumerable? [英] Why do we need IEnumerator and IEnumerable?

查看:88
本文介绍了为什么我们需要IEnumerator和IEnumerable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,所以我只是在IEnumeratorIEnumerable中工作.现在,MSDN表示这些事情的主要目标是遍历客户集合.

Ok so I was just working through the IEnumerator and IEnumerable. Now the MSDN says that the main objective of these things is to iterate through a customer collection.

很公平,但是我能够遍历一个自定义集合而无需使用任何一个(或者至少我想这样)

Fair enough I was however able to iterate through a custom collection without the use of either (or at least I'd like to think so)

namespace ienumerator
{

class person
{
    public person(string first, string second)
    {
        fname = first;
        lname = second;
    }
    public string fname { get; set; }
    public string lname { get; set; }
}

class person_list
{
    public person[] list;
    public person_list(person[] per)
    {
        list = new person[per.Length];
        for (int i = 0; i < per.Length; i++)
        {
            list[i] = per[i];
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        person[] names = new person[3]
        {
            new person("some","one"),
            new person("another","one"),
            new person("sss","ssdad"),
        };

        person_list list_of_names = new person_list(names);
        int i = 0;
        while (i < list_of_names.list.Length)
        {
            Console.WriteLine(list_of_names.list[i].fname);
            i++;
        }
        Console.Read();
    }
 }
}

所以我的理解有缺陷,上面的内容给了我实现IEnumeratorIEnumerable后获得的相同结果.

So what is flawed in my understanding, the above is giving me the same result that I achieve after implementing IEnumerator and IEnumerable.

推荐答案

但是我能够遍历自定义集合而无需使用任何一个

I was however able to iterate through a custom collection without the use of either

当然可以在没有界面的情况下迭代您自己的集合; 如果不能,那么如何实现该接口?

Of course you can iterate your own collection without the interface; if you couldn't, then how would you implement the interface?

作为代码实现者,您没有实现您的便利的接口.您实现该代码是为了方便代码的消费者.该界面的意思是注意客户:您可以枚举此集合的内容,而不必了解我如何实现它".

You, as a code implementor, do not implement an interface for your convenience. You implement it for the convenience of the consumer of your code. The interface means "attention customer: you can enumerate the contents of this collection without having to know anything about how I implemented it".

这就是接口的目的:它提供了一种抽象,允许您的代码使用者使用它而不必了解它的工作方式.

That's the purpose of an interface: it provides an abstraction that allows consumers of your code to use it without having to understand how it works.

这篇关于为什么我们需要IEnumerator和IEnumerable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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