123
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Indexators { class Program { static void Main(string[] args) { // PeopleCollection behave like array !!! PeopleCollection people = new PeopleCollection(); people[0] = new Person(123, "123", "123"); people[1] = new Person(123, "123", "123"); people[2] = new Person(123, "123", "123"); people[3] = new Person(123, "123", "123"); for (int i = 0; i < people.Count; i++) { Console.WriteLine(people[i].FirstName); } Console.ReadLine(); } } public class Person { public int Age { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public Person() { } public Person(int age, string firstName, string lastName) { Age = age; FirstName = firstName; LastName = lastName; } public override string ToString() { return ("Age=" + Age); // return base.ToString(); } } public class PeopleCollection : IEnumerable { private ArrayList ArrayListPeople = new ArrayList(); public Person GetPerson(int pos) { return (Person)ArrayListPeople[pos]; } public void AddPerson(Person p) { ArrayListPeople.Add(p); } public void ClearPeople() { ArrayListPeople.Clear(); } // foreach support public IEnumerator GetEnumerator() { return ArrayListPeople.GetEnumerator(); } public int Count { get { return ArrayListPeople.Count; } } // adding indexator - then collection will have behaviour like array public Person this[int index] { get { return (Person)ArrayListPeople[index]; } set { ArrayListPeople.Insert(index, value); } } } } |