using System;
using System.Collections;
using System.Collections.Generic;
class Program {
// *** было: ***
// коллекция хранила object, поэтому каждый элемент приходилось
// приводить обратно, а неверный элемент обнаруживался
// только во время выполнения
static int SumOld(ArrayList numbers) {
int total = 0;
foreach (object o in numbers)
total += (int)o; // распаковка на каждом элементе
return total;
}
// *** в версии 2.0: ***
// List<T> хранит тип элемента, поэтому его проверяет компилятор
static int SumNew(List<int> numbers) {
int total = 0;
foreach (int n in numbers) // без приведения и упаковки
total += n;
return total;
}
// свои методы и классы тоже принимают параметры типа
static T Largest<T>(T a, T b) where T : IComparable<T> {
return a.CompareTo(b) >= 0 ? a : b;
}
static void Main() {
ArrayList old = new ArrayList();
old.Add(1); old.Add(2); old.Add(3);
old.Add("four"); // компилируется, и SumOld на этом падает
Console.WriteLine(old.Count);
List<int> fresh = new List<int>();
fresh.Add(1); fresh.Add(2); fresh.Add(3);
// fresh.Add("four"); // не скомпилируется
Console.WriteLine(SumNew(fresh));
Dictionary<string, int> ages = new Dictionary<string, int>();
ages["Ann"] = 31;
Console.WriteLine(ages["Ann"]);
Console.WriteLine(Largest(6, 7));
}
}