标签:
3.1 为什么需要泛型
3.2 日常使用的简单泛型
3.2.1通过例子来学习: 泛型字典
class DictionaryDemo { static Dictionary<string,int> CountWords(string text) { Dictionary<string,int> frequencies; frequencies = new Dictionary<string,int>(); string[] words = Regex.Split(text, @"\W+"); foreach (string word in words) { if (frequencies.ContainsKey(word)) { frequencies[word]++; } else { frequencies[word] = 1; } } return frequencies; } static void Main() { string text = @"Do you like green eggs and ham? I do not like them, Sam-I-am. I do not like green eggs and ham."; Dictionary<string, int> frequencies = CountWords(text); foreach (KeyValuePair<string, int> entry in frequencies) { string word = entry.Key; int frequency = entry.Value; Console.WriteLine("{0}: {1}", word, frequency); } } }
3.2.2 泛型类型和类型参数
var type= typeof(Dictionary<,>);
非泛型蓝图 | 泛型蓝图 | |
Dictionary<TKey,TValue>(未绑定泛型类型) | ||
指定类型参数 | 指定类型参数 | |
Dictionary<string,int>(已构造类型) | Dictionary<byte,long>(已构造类型) | |
实例化 | 实例化 | 实例化 |
Hashtable实例 | Dictionary<string,int>实例 | Dictionary<byte,long>实例 |
泛型类型中的方法签名 | 类型参数被替换之后的方法签名 |
void Add (TKey key,Tvalue value) | void Add (string key,int value) |
注意上表中的方法并不是泛型方法,只是泛型类型中的普通方法,只是凑巧使用了作为类型一部分声明的类型参数。
3.2.3 泛型方法和判读泛型声明
class ListConvertAll { static double TakeSquareRoot(int x) { return Math.Sqrt(x); } static void Main() { List<int> integers = new List<int>(); integers.Add(1); integers.Add(2); integers.Add(3); integers.Add(4); Converter<int, double> converter = TakeSquareRoot; List<double> doubles = integers.ConvertAll<double>(converter); foreach (double d in doubles) { Console.WriteLine(d); } } }
class GenericMethodDemo { static List<T> MakeList<T>(T first, T second) { List<T> list = new List<T>(); list.Add(first); list.Add(second); return list; } static void Main() { List<string> list = MakeList<string>("Line 1", "Line 2"); foreach (string x in list) { Console.WriteLine(x); } } }
3.3深化与提高
3.3.1类型约束
标签:
原文地址:http://www.cnblogs.com/leonhart/p/4661661.html