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));
}
}