. NET generics may be a reference to the C + + generic template, which enables the abstraction of types, generics, and decoupling between types and methods. One of the most classic uses is to implement generic processing for each domain model in the base interface and base class for different domain models in a three-tier architecture.
This article mainly includes:
Why generics are required
※ No generic type
※ Use generic type
※ The operation nature of the generic type
Generic Syntax
A typical generic class
Why generics are required
No generics
See a method for comparing types.
Public class Calculator { publicstaticbool AreEqual (intint value2) { return value1 = = value2; } }
Called on the client.
classProgram {Static voidMain (string[] args) { BOOLresult = Calculator.areequal (1,2); if(Result) {Console.WriteLine ("Equal"); } Else{Console.WriteLine ("Unequal"); } console.readkey (); } }
Operation Result: Unequal
Disadvantage one without generics: not type-safe
If we want to use the current method to compare string types.
bool result = Calculator.areequal ("A""B");
At this point, see the compiler error. From this point of view, the AreEqual () method is not a type-safe method, and when the string type is entered, the compiler will error.
If you change the parameter type of the AreEqual () method to object, the compiler will no longer give an error.
Public class Calculator { publicstaticbool AreEqual (objectobject value2) { return value1 = = value2 ;} }
The operation is also normal.
Disadvantages of no generics two: packing and unpacking results in reduced performance
Now, for AreEqual (object value1, Object value2), there is no problem from the method itself, but when the client calls, for example, we want to compare the value type.
bool result = Calculator.areequal (12);
At run time, a "boxing" operation occurs when the integer value type parameters 1 and 2 are passed, assigned to the reference type parameter value1 and value2 in AreEqual (object value1, Object value2). When you convert a reference type to a value type, a "unboxing" operation occurs, which results in a decrease in performance.
Using generics
Change the AreEqual () to a generic method.
Public class Calculator { publicstaticbool areequal<t>(t value1, T value2) { return value1. Equals (value2); } }
As a result, the client can do this:
bool result = calculator.areequal<string> ("a""a" "bool result = calculator.areequal<int> (53 );
Thus, the benefits of using generics are:
1. The decoupling of the method and the type is realized.
2, does not cause the type conversion, avoids the packing in the unpacking causes the performance question.
3. Generics guarantee the absolute safety of the type.
Of course, you can also place the T position on the class:
Public class Calculator<t> { publicstaticbool AreEqual (t value1, T value2 ) { return value1. Equals (value2); } }
Then use this:
bool result = calculator<string;. AreEqual ("a""a"bool result = Calculator <int. AreEqual (12);
The run-time nature of generics
There are specialized IL directives in the CLR that support generic operations.
→ Generate IL code and metadata at initial compile time, T is just a type placeholder, not instantiated at compile time
→jit Replace T-placeholders in metadata with actual types at compile time
→ convert metadata to local code
Generic Syntax
class where New () { private t[] _items; Public T myData; Public MyArray () { default(T); } Public void Add (T Item) {}}
Create a generic instance to specify the actual data type:
myarray<int32> Myarr = new myarray<int32> ();
The default value of a value type is 0, the default value of the reference type is null, and the generic default value is used:
MyData = Default (T);
Generic constraints:
T: base class name, which represents a derived class that must be a base class name
T:new (), indicating that a parameterless constructor must be in place, and that the new () constraint must be placed on the last face
T:struct, which indicates that a value type must be
T:class, which indicates that a reference type must be
T: The interface name, which indicates that the interface must be implemented or implemented on the interface
A generic class is essentially still a class and can still inherit:
Internal class where T:icomparable<t>class myarray<t>: ArrayList
A typical generic class
In the System.Collections.Generic namespace and System.Collections.ObjectModel, different generic classes and generic interfaces are defined, many of which are collection classes.
List<t> corresponding ArrayList collection class
Sortedlist<tkey, tvalue> corresponds to SortedList collection class
Queue<t> Advanced first-out collection class
Stack<t> last-in-first-out collection class
Collection<t> base class for custom generic collections
Dictionary<tkey, tvalue> corresponds to Hashtable collection class
Resources:
You must know. NET (2nd edition), author Wang Tao.