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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StringIndexators { class Program { static void Main(string[] args) { // PeopleCollection behave like array !!! PeopleCollection2 people2 = new PeopleCollection2(); people2["123"] = new Person(123, "123", "123"); people2["1234"] = new Person(123, "1234", "123"); people2["12345"] = new Person(123, "12345", "123"); people2["123456"] = new Person(123, "123456", "123"); Person somePerson = people2["123"]; Console.WriteLine(somePerson.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); } } } public class PeopleCollection2 : IEnumerable { private Dictionary<string, Person> dictPeople = new Dictionary<string, Person>(); // adding indexator - then collection will have behaviour like array public Person this[string name] { get { return (Person)dictPeople[name]; } set { dictPeople[name] = value; } } public void ClearPeople() { dictPeople.Clear(); } public int Count { get { return dictPeople.Count; } } // foreach support public IEnumerator GetEnumerator() { return dictPeople.GetEnumerator(); } } } |