//用来统计单词的个数
//泛型类型包括(类,接口,委托和结构---没有泛型枚举)和泛型方法
//用来统计单词的个数
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;// 若用c#1的HASHTABLE的相似的键和值属性的非返型dictionaryentry,但是word和frequency需要强制类型转换:因为Key,Value都是以object类型返回的
Console.WriteLine("{0}: {1}", word, frequency);
}
}
}
//泛型方法: 虽然dictionary<tkey,tvalue>没有泛型方法,但它的近亲list<T>有的
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 Represents a method that converts an object from one type to another type.
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);
}
}
}
// 类型约束:
1: 引用类型约束: T:class 用于确保使用的类型实参是引用类型:
2:值类型约束: T:struct 用于确保使用的类型实参是值类型:将包括枚举,但是它将可空类型排除在外:
3: 构造函数类型约束: 表示为T: new(); 必须是所有引用类型参数的最后一个约束,仅核对所有的类型实参有一个
无参数构造函数,这个构造函数可用于创建类型的实例:
4: 派生类型的约束: (有点难以理解)
5.组合约束:
//泛型方法类型实参的判断:
调用泛型方法时,指定类型的实参常常会显得多余的,根据向方法传递的实参,很容易看出传递的类型实参
应该是什么:在调用方法的时候,不需要显式声明类型实参,:必须强调: 类型推断只适用于泛型方法,不适用于类型,
比如上句:
List<string> list = MakeList<string>("Line 1", "Line 2");
可以简单写成: List<string> list = MakeList("Line 1", "Line 2");
//以泛型方式将一个给定的值和默认值进行比较: 给出的类型判断和派生类型约束的实例:
class DefaultValueComparison
{
static int CompareToDefault<T>(T value)
where T : IComparable<T>
{
return value.CompareTo(default(T));
}
static void Main()
{
Console.WriteLine(CompareToDefault("x"));
Console.WriteLine(CompareToDefault(10));
Console.WriteLine(CompareToDefault(0));
Console.WriteLine(CompareToDefault(-10));
Console.WriteLine(CompareToDefault(DateTime.MinValue));
}
}
// // 如果一个类型参数被约束成值类型,就完全不能为它使用==和!=,如果被约束成引用类型,那么具体执行的比较完全
//取决于类型参数被约束成什么类型,如果它只是一个引用类型,那么执行的是简单的引用比较,
//如果它进一步约束成一个重载了==和!=操作符指定的特定的类型派,就会使用重载的操作符
// 但要注意的是: 假如调用者指定的类型实参恰巧也进行了重载,那些额外的重载符号是不会使用的:
// 用==和!=进行引用比较
class OperatorOverloading
{
static bool AreReferencesEqual<T>(T first, T second)
where T : class
{
return first == second;
}
static void Main()
{
string name = "Jon";
string intro1 = "My name is " + name;
string intro2 = "My name is " + name;
Console.WriteLine(intro1 == intro2);
Console.WriteLine(AreReferencesEqual(intro1, intro2));
}
}
----作为实现泛型:
// 作为了“实现泛型”(实际上实现了中级泛型)这一主题结束,先面给出一个的例子:
//它实现了有用的泛型类型
[Description("Listing 3.06")]
//需要对值进行比较时,有两个相当的有用的类,分别是: EqualityComparer:(适合对字典进行比较和哈希处理)和
// IComparer<T>(适合于排序)
//这两个类的default属性能返回一个实现,该实现都能为特定的类型采取正确的(比较操作)
// EqualityComparer<T>的例子:
public sealed class Pair<TFirst, TSecond> : IEquatable<Pair<TFirst, TSecond>> // IEquatable<Pair<TFirst, TSecond>>支持排序
{
private static readonly IEqualityComparer<TFirst> FirstComparer =
EqualityComparer<TFirst>.Default;
private static readonly IEqualityComparer<TSecond> SecondComparer =
EqualityComparer<TSecond>.Default;
private readonly TFirst first;
private readonly TSecond second;
public Pair(TFirst first, TSecond second)
{
this.first = first;
this.second = second;
}
public TFirst First { get { return first; } }
public TSecond Second { get { return second; } }
public bool Equals(Pair<TFirst, TSecond> other)
{
return other != null &&
FirstComparer.Equals(this.First, other.First) &&
SecondComparer.Equals(this.Second, other.Second);
}
public override bool Equals(object o)
{
return Equals(o as Pair<TFirst, TSecond>);
}
public override int GetHashCode()
{
return FirstComparer.GetHashCode(first) * 37 +
SecondComparer.GetHashCode(second);
}
}
public static class Pair
{
public static Pair<TFirst, TSecond> Of<TFirst, TSecond>(TFirst first, TSecond second)
{
return new Pair<TFirst, TSecond>(first, second);
}
}
}
//高级泛型:
//静态字段和静态构造函数:
// 若在someclass中静态字段x:不管创建多少个someclass实例,也不管派生多个类型,都只型号有一个someclass.x字段:
//它如何映射到泛型:
//不同的泛型都有它自己的静态字段集
class StaticFieldPerClosedType
{
class TypeWithField<T>
{
public static string field;
public static void PrintField()
{
Console.WriteLine(field + ": " + typeof(T).Name);
}
}
static void Main()
{
TypeWithField<int>.field = "First";
TypeWithField<string>.field = "Second";
TypeWithField<DateTime>.field = "Third";
TypeWithField<int>.PrintField();
TypeWithField<string>.PrintField();
TypeWithField<DateTime>.PrintField();
}
}
//静态字段和静态构造函数:
// 若在someclass中静态字段x:不管创建多少个someclass实例,也不管派生多个类型,都只型号有一个someclass.x字段:
//它如何映射到泛型:
//不同的泛型都有它自己的静态字段集
class StaticFieldPerClosedType
{
class TypeWithField<T>
{
public static string field;
public static void PrintField()
{
Console.WriteLine(field + ": " + typeof(T).Name);
}
}
static void Main()
{
TypeWithField<int>.field = "First";
TypeWithField<string>.field = "Second";
TypeWithField<DateTime>.field = "Third";
TypeWithField<int>.PrintField();
TypeWithField<string>.PrintField();
TypeWithField<DateTime>.PrintField();
}
}
// 基本规则: 每个封闭类型有一个静态字段”同样的规则: 也适用于静态初始化程序:
//和静态构造函数
//--嵌套泛型类型的静态构造函数:
class StaticConstructors
{
class Outer<T>
{
public class Inner<U, V>
{
static Inner()
{
Console.WriteLine("Outer<{0}>.Inner<{1},{2}>",
typeof(T).Name,
typeof(U).Name,
typeof(V).Name);
Console.ReadLine();
}
Inner()
{
Console.Write("执行构造函数的时候是不会执行构造函数");
Console.ReadLine();
}
public static void DummyMethod()
{
Console.WriteLine("print some th");
Console.ReadLine();
}
}
}
static void Main()
{
Outer<int>.Inner<string, DateTime>.DummyMethod();
Outer<string>.Inner<int, int>.DummyMethod();
Outer<object>.Inner<string, object>.DummyMethod();
Outer<string>.Inner<string, object>.DummyMethod();
Outer<object>.Inner<object, string>.DummyMethod();
Outer<string>.Inner<int, int>.DummyMethod();
}
}
}
//和任何类型一样,静态构造函数只执行一次:
泛型迭代:
class CountingEnumerableExample
{
class CountingEnumerable : IEnumerable<int>
{
public IEnumerator<int> GetEnumerator() // 隐式实现”
{
return new CountingEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() //IEnumerable.GetEnumerator: IEnumerable接口名: 实现接口所规定的方法和属时附加接口名作为前缀,即称为”显式接口实现“---
{
return GetEnumerator();
}
}
class CountingEnumerator : IEnumerator<int>
{
int current = -1;
public bool MoveNext()
{
current++;
return current < 10;
}
public int Current //隐式实现Current
{
get { return current; }
}
object IEnumerator.Current //IEnumerator.Current 显式实现:
{
get { return Current; }
}
public void Reset()
{
throw new NotSupportedException();
}
public void Dispose()
{
}
}
static void Main()
{
CountingEnumerable counter = new CountingEnumerable();
foreach (int x in counter)
{
Console.WriteLine(x);
}
}
//
反射泛型方法:
//反射泛型方法:
class GenericMethodReflection
{
public static void PrintTypeParameter<T>()
{
Console.WriteLine (typeof(T));
}
static void Main()
{
Type type = typeof(GenericMethodReflection);
MethodInfo definition = type.GetMethod("PrintTypeParameter");
MethodInfo constructed;
constructed = definition.MakeGenericMethod(typeof(string));
constructed.Invoke(null, null);
}
}
.net2.0中的泛型集合类:
list<T>
dictionary<tkey,tvalue>
queue<t>
stact<t>
linkedlist<t>
协变性和逆变性的缺乏:
缺乏操作符约束或者"数值"约束: