Home   Cover Cover Cover Cover
 

Iterieren ├╝ber Felder einer Klasse

A03.cs
//==========================================================
// Iterating over the fields of a class
//==========================================================

using System;
using System.Collections.Generic;

//----------------------------------------------------------
// class Person
//----------------------------------------------------------
class Person {
  string firstName;
  string lastName;
  string street;
  string city;
  int zipCode;
  
  // creates a person
  public Person(string firstName, string lastName, string street, string city, int zipCode) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.street = street;
    this.city = city;
    this.zipCode = zipCode;
  }
  
  // iterator over all field of an object
  public IEnumerator<string> GetEnumerator() {
    yield return firstName;
    yield return lastName;
    yield return street;
    yield return city;
    yield return zipCode.ToString();
  }
  
}

//----------------------------------------------------------
// test program
//----------------------------------------------------------
class Test {
  
  public static void Main() {
    Person person = new Person("John", "Doe", "High Street", "London", 12345);
    foreach (string field in person)
      Console.WriteLine(field);
  }
}