当前位置:首页 > Windows程序 > 正文

C# in depth ( 第三章 用泛型实现参数化类型)

2021-03-29 Windows程序

JIT能够聪明地处理值类型,能消除很多情况下的装箱和拆箱处理。

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 泛型类型和类型参数

泛型有两种形式

泛型类型(类,接口,委托和结构)

泛型方法

类型参数  类型参数是真实类型的占位符 在Dictionary<TKey,TValue>中类型参数是TKey和TValue。

类型实参 使用泛型类型或方法时,要用真实的类型替代,,这些真实的类型成为类型实参(type argument)在代码清单中类型实参是string(代替TKey)和int(代替TValue)

未邦定泛型类型(unbound generic type) 如果没有为泛型类型参数提供类型实参,那么这就是一个未邦定泛型类型(unbound generic type)

在C#代码中唯一能看见未邦定代码的地方就是typeof 

var type= typeof(Dictionary<,>);

如果指定了类型实参,该类型就称为一个已构造的类型(constructed type), 已构造类型又可以是开放或封闭的。

开放类型(open type)还包含一个类型参数

封闭类型(closed type)则不是开放的,类型的每个部分都是明确的。

未绑定泛型类型相当于已构造类型的蓝图。已构造类型又是实际对相的蓝图,这一点和非泛型类型的作用是相似的

非泛型蓝图   泛型蓝图  
    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)  

注意上表中的方法并不是泛型方法,只是泛型类型中的普通方法,只是凑巧使用了作为类型一部分声明的类型参数。

泛型类型可以重载MyType,MyType<T>,MyType<T,U>,MyType<T,U,V> 所有这些定义可以被放到同一个命名空间,类型参数的名称并不重要,重要的是个数,泛形方法也一样。

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

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/69539.html