实现枚举接口 [英] Implementing the Enumeration Interfaces

查看:277
本文介绍了实现枚举接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

The code:

class Person
   {
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public Person(string firstName, string lastName)
       {
           FirstName = firstName;
           LastName = lastName;
       }
       public override string ToString()
       {
           return FirstName + " " + LastName;
       }
   }
   class People : IEnumerable<Person>
   {
       Person[] people;
       public People(Person[] people)
       {
           this.people = people;
       }
       public IEnumerator<Person> GetEnumerator()
       {
           for (int i = 0; i < people.Length; i++)
           {
               yield return people[i];
           }
       }
       IEnumerator IEnumerable.GetEnumerator()
       {
           return GetEnumerator();
       }
   }



所以类实现了接口的IEnumerable 。令我困惑的是两种方法(我们可以称之为方法吗?)。


So class People implemented the interface IEnumerable. What I am confused is the two methods(Can we call them methods?).

public IEnumerator<Person> GetEnumerator()
        {
            for (int i = 0; i < people.Length; i++)
            {
                yield return people[i];
            }
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }



我们应该称他们为方法吗?因为IEnumerable具有默认方法 GetEnumerator。

我们可以直接使用它。如果我们改变行为,那么我们需要添加覆盖修饰符。

我们应该:


Should we call them methods? Because IEnumerable has the default method GetEnumerator.
We can directly use it. If we change the behavior then we need to add the override modifier.
Should we:

public override GetEnumerator()
{
 //blah blah
}

推荐答案

是的,它们是方法。当你通过IEnumerable调用它们时(例如使用 foreach ),你正在调用它们的版本,因为IEnumerable是一个接口而且根本不实现任何代码。这就是为什么你必须实现它们:这样它们就可以被调用了!



是的,你可以自己打电话给你:但你通常不必这样做。几乎在所有情况下,要求您将类添加到类中的代码都会为您调用它们。
Yes, they are methods. When you call them via IEnumerable (for example by using foreach) you are calling your version of them, since IEnumerable is an interface and doesn't implement any code at all itself. That's why you have to implement them: so that they are there to be called!

Yes, you could call them yourself: but you don't normally have to. The code that requires you to add the interface to your class calls them for you in nearly all cases.


这篇关于实现枚举接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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