我一直在想是否有可能让说State
类实施IEnumerable<Person>
,IEnumerable<City>
所以我可以通过 foreach 以及所有城市让所有居住在该州的人。它甚至不会编译这样说:(Error 1 'ConsoleApplication1.City' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'
奇怪)......这是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Person
{
}
class City : IEnumerable<Person>
{
// City has citizens:
Person[] citizens;
IEnumerator<Person> IEnumerable<Person>.GetEnumerator()
{
foreach (Person p in citizens)
yield return p;
}
}
class State : IEnumerable<Person>, IEnumerable<City>
{
// State has cities:
City[] cities;
IEnumerator<Person> IEnumerable<Person>.GetEnumerator()
{
foreach (City c in cities)
foreach (Person p in c)
yield return p;
}
IEnumerator<City> IEnumerable<City>.GetEnumerator()
{
foreach (City c in cities)
yield return c;
}
}
class Program
{
static void Main(string[] args)
{
State s = new State();
foreach (Person p in s) ;
foreach (City c in s) ;
}
}
}