Let's discuss the usage of generics today. First, let's talk about the concept of generics. In a popular language, generics are actually a parameter of a class, but the parameter must be a class rather than an object. Many people may not understand the role of T in generics. The role of T in generics is equivalent to a placeholder. Specifically, T is a type placeholder. Any place where T appears will be replaced with the type you passed.
Let's write an example of generics to let everyone experience the power of generics.
First, let's look at the commonly used list <t> generic set.
01, list <t> set, where T can be of any type (INT, String, array type, or even user-defined class type)
List <string> intlist = new list <string> ();
Intlist. Add ("Li Xiaoling ");
Intlist. Add ("Zhang Ziyi ");
Foreach (string item in intlist)
{
Console. writeline (item );
}
You can also use a set initiator similar to the array initiator when declaring list <t>.
Example: List <string> namelist = new list <string> () {"Jack", "Rose", "Harvard "};
(This feature is used in. net3.0 and later versions)
List <t> common methods:
1. To add an element to the generic type: Use the add () method.
Add multiple elements: Use the addrange () method
2. Insert an element at a specified position using the insert () method
3. The access element can be indexed or traversed cyclically using foreach.
4. You can use the remove () or removat () Methods to delete elements. You can use the clear () method to delete all elements.
Next, let's look at the following key-Value Pair generic set dictionary <key, value>
C # also provides a generic type for hashtable, which is called a dictionary ".
Dictionary <K, V> features of data storage:
1. data is stored in a similar way as a hash table, and elements are stored using key/value.
2. The key must be unique. The value cannot be null. However, if the value is of the reference type, the value can be null.
Main attribute: Count: obtains the key/value logarithm.
Keys: a set of keys.
// 02, Dictionary <K, V> set
Dictionary <string, string> DIC = new dictionary <string, string> ();
Dic. Add ("01", "bruce lee ");
Dic. Add ("02", "Jet Li ");
// Traverse the key
Foreach (string item in DIC. Keys)
{
Console. writeline ("key" + item + "value" + DIC [item]);
}
// One-time key and value Traversal
Foreach (keyvaluepair <string, string> item in DIC)
{
Console. writeline ("key" + item. Key + "value" + item. value );
}
At this time, you may have questions. Why should we use generics?
Generic has three advantages:
1. ImplementationAlgorithm.
Before the emergence of generics, when we customize a set of strong types to ensure performance security, we need to create almost identical custom sets for each type. This will result in repetitive work and poor maintainability.
2. Avoid unpacking and packing.
As you can understand, using arraylist and hashtable to access variables will result in frequent packing (converting the value type to the reference type) and unpacking (converting the reference type to the value type) operations, it has an impact on performance.
3. type security (the parameter type is automatically checked during compilation)
Features of generics:
The generic model defines the data type of the operation as a parameter. The type parameter makes it possible to design the following classes and methods. These classes and Methods delay the specified one or more types to the client.CodeDeclare and instantiate classes or methods.
Use Where constraints
You can use the where constraint type parameter:
Where T: In struct, T must have the system. valuetype value type in its inheritance chain.
Where T: in class, T must be of the reference type.
Where T: In New (), T must have a default constructor. The constraint must be listed at the end of multiple types of constraints.
Where T: In nameofbaseclass, T must be derived from the class specified by nameofbaseclass.
Of course, generics can be used not only in classes, but also in class methods. They can automatically adapt to various parameters according to the type of method parameters. Such a method is called a generic method.
Public class stack2
{
Public void push <t> (stack <t> S, Params T [] P)
{
Foreach (t in P)
{
S. Push (t );
}
}
}
The original class stack can only push one data at a time. This class stack2 extends the stack function and can push multiple data into the stack at a time. The Push method is a generic method. The call example of this method is as follows:
Stack <int> stack = new stack <int> (100 );
Stack2 mystack2 = new stack2 ();
Mystack2.push (x, 1, 2, 3 );
String STR = string. empty;
For (INT I = 0; I <3; I ++)
{
STR + = stack. Pop (). tostring ();
}
The STR value output is 64321.