Csharp/CSharp Tutorial/Class/IEnumerable — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 12:16, 26 мая 2010
IEnumerable<T>
using System;
using System.Collections.Generic;
public class Employee {
public string Name;
public string Title;
public Employee(string name, string title) {
Name = name;
Title = title;
}
public override string ToString() {
return string.Format("{0} ({1})", Name, Title);
}
}
public class Team {
private List<Employee> teamMembers = new List<Employee>();
public IEnumerator<Employee> GetEnumerator() {
foreach (Employee tm in teamMembers) {
yield return tm;
}
}
public IEnumerable<Employee> Reverse {
get {
for (int c = teamMembers.Count - 1; c >= 0; c--) {
yield return teamMembers[c];
}
}
}
public IEnumerable<Employee> FirstTwo {
get {
int count = 0;
foreach (Employee tm in teamMembers) {
if (count >= 2) {
yield break;
} else {
count++;
yield return tm;
}
}
}
}
public void AddMember(Employee member) {
teamMembers.Add(member);
}
}
public class MainClass {
public static void Main() {
Team team = new Team();
team.AddMember(new Employee("C", "C"));
team.AddMember(new Employee("N", "K"));
team.AddMember(new Employee("N", "S"));
foreach (Employee member in team) {
Console.WriteLine(" " + member.ToString());
}
foreach (Employee member in team.FirstTwo) {
Console.WriteLine(" " + member.ToString());
}
foreach (Employee member in team.Reverse) {
Console.WriteLine(" " + member.ToString());
}
}
}
Supporting foreach with IEnumerable and IEnumerator
using System;
using System.Collections;
class Rainbow : IEnumerable, IEnumerator
{
private short IteratorIndex = -1;
public IEnumerator GetEnumerator()
{
return this;
}
public object Current
{
get
{
switch(IteratorIndex)
{
case 0:
return "Red";
case 1:
return "Orange";
case 2:
return "Yellow";
case 3:
return "Green";
case 4:
return "Blue";
case 5:
return "Indigo";
case 6:
return "Violet";
default:
return "*** ERROR ***";
}
}
}
public bool MoveNext()
{
IteratorIndex++;
if(IteratorIndex == 7)
return false;
return true;
}
public void Reset()
{
IteratorIndex = -1;
}
public static void Main()
{
Rainbow MyRainbow = new Rainbow();
foreach(string ColorName in MyRainbow)
Console.WriteLine(ColorName);
}
}