Use generics to implement parameterized types
1. The generics are better checked during compilation, which can eliminate a lot of packing and unpacking.
2. Generic dictionary <tkey, tvalue>
1 static Dictionary<string,int> CountWords(string text) 2 { 3 Dictionary<string,int> frequencies; 4 frequencies = new Dictionary<string,int>(); 5 6 string[] words = Regex.Split(text, @"\W+"); 7 8 foreach (string word in words) 9 {10 if (frequencies.ContainsKey(word))11 {12 frequencies[word]++;13 }14 else15 {16 frequencies[word] = 1;17 }18 }19 return frequencies;20 }21 22 ...23 string text = @"Do you like green eggs and ham?24 I do not like them, Sam-I-am.25 I do not like green eggs and ham.";26 27 Dictionary<string, int> frequencies = CountWords(text);28 foreach (KeyValuePair<string, int> entry in frequencies)29 {30 string word = entry.Key;31 int frequency = entry.Value;32 Console.WriteLine("{0}: {1}", word, frequency);33 }
3. There are two generic types: Generic Type (class, interface, delegate, and structure, but no generic enumeration) and generic method.
Type parameters are placeholders of real types. These real types are called type argument ). When using a generic type or method, it should be replaced by a real type. When the generic dictionary is in use, the string parameter of the type replaces tkey, And the int parameter replaces tvalue.
4. Type Constraints
Reference Type constraints: struct refsample <t> where T: class constraints T types are reference types. Of course, t can also be restricted to interfaces, arrays, delegates, or other known reference types.
Valid constraints: refsample <idisposable> refsample <string> refsample <int []>
Invalid constraint: refsample <guid> refsample <int>
The constrained type is different from the type itself. The type here is a value type.
Value Type constraints: Class valsample <t> where T: struct constraints t are value types, including enumeration, but can be empty.
Valid constraint: valsample <int> valsample <filemode>
Invalid constraint: valsample <Object> valsample <stringbuilder>
Constructor constraint: T: New (), which must be the last constraint of all parameter constraints. It checks whether the real parameters of the type have the no-argument constructor used to create the type instance.
Applicable to: All value types; all non-static and non-abstract classes without explicitly declaring constructor; all non-abstract classes that explicitly declare a common non-argument constructor.
Conversion Type constraints:
Combined constraint case:
5. Advanced generic
Static Field: If the static field X is declared in someclass, no matter how many instances are created in someclass or how many types are derived from someclass, there is only one someclass. X field.
How does JIT handle generics?
Generic iteration: in C #2, traversing a generic set (list <int>) composed of value elements is not boxed at all.
Reflection and generics: typeof, system. Type