Usage of generics

Source: Internet
Author: User

Generic (generic) is an extension of the CLR type system. It is used to define types that do not specify certain details. Actually,CodeIt is generic.

Using Generics can avoid two common problems: Code redundancy and ambiguous compiler errors that plague developers. Assume that the collection class sortedlist is a collection referenced by objects, and genericsortedlist <t> is a set of any type. Using Generics has the following obvious advantages.

(1) type security

When you add a string to a sortedlist type set, the string is implicitly converted to an object. Similarly, if A String object is retrieved from the list, it must be forcibly converted from the object reference to the string reference at runtime. This will cause a lack of type security during compilation, so that the written code is prone to errors. Conversely, if you use genericsortedlist <string> (the T type is set to string), all adding and searching methods will be referenced using string. In this way, you can check whether the element type is correct during compilation.

(2) binary code reuse

For maintenance purposes, developers can choose to use sortedlist to derive sortedlistofstring from it to implement type security during compilation. There is a problem with this method, that is, you must write new code for each type that requires the type security list, which will quickly become a very laborious task. To use genericsortedlist <t>, all the operations that need to be performed are to instantiate the type with the required element type as T. There is also an additional value for generic code, that is, it is generated at runtime. Therefore, two extensions of irrelevant element types (such as genericsortedlist <string> and genericsortedlist <filestream>) most of the code that can be re-compiled using the same real-time (JIT. CLR only processes details, so that the code is no longer bloated.

(3) Performance

If you can perform type check during compilation, rather than during runtime, the system performance will be significantly enhanced. In managed code, forced conversions between references and values can cause both packing and unpacking, and prevent such forced conversions from negatively affecting performance. If you perform a quick sorting benchmark for an array composed of 1 million integers, you will find that the generic method is much faster than the non-generic method. This is because it completely avoids packing these values. If you sort arrays composed of string references in the same way, you do not need to perform a type check at runtime. Therefore, using the generic method greatly improves the performance.

(4) Clarity

The clarity of generics is reflected in many aspects. Constraints are a function of generics. They disable incompatible extensions of generic code, there are no ambiguous compiler errors that plague C ++ template users. In genericsortedlist <t>, the collection class has a constraint that allows the collection class to only process T types that can be compared and sorted accordingly. Likewise, generic methods can be called using the type inference function without any special syntax. Of course, the type security during compilation can enable the applicationProgramThe code is clearer.

Generic definition

CLR supports multiple typesProgramming LanguageTherefore, CLR generics also have multiple syntaxes. However, no matter which syntax is used, generic code written in a CLR-oriented language can also be used by programs written in other CLR-oriented languages.

The syntax for defining generic code is:

[Access modifier] [return type] generic support type generic name <type parameter list>

CLR supports generic classes, structures, methods, interfaces, and delegation. The generic name must comply with the identifier definition. Angle brackets indicate the list of type parameters. Angle brackets follow the name of a generic type or member. Similarly, there are one or more type parameters in the type parameter list, in the form of <t, u,…>.

Example 1: Define a generic class

  1   Class  Node  <  T  >  
2 {
3 T data;
4 Node < T > Next;
5 }
6  

 

Example 2: Define a generic Method

  1   Void  Swap  <  T >  (  Ref  T Item1,  Ref  T item2)
2 {
3 T temp = Item1;
4 Item1 = Item2;
5 Item2 = Temp;
6 }
7  

 

Generic references

When referencing a generic type, you can also change unspecified types to the specified types that can be recognized by the system. Example 3 and Example 4 are reference examples for example 1 and Example 2 respectively.

 

Example 3: reference a generic class

  1 ClassNode8bit: Node<Byte>
2 {
3 ...
4 }
5  

Example 4: reference a generic Method

  1 Decimal d1=0, D2=2;
2 Swap<Decimal>(RefD1,RefD2 );

 

The example shows that when defining a class or method, you can use the wildcard <t> to represent any type, and specify a specific type When referencing. In Example 6, when the Code calls the generic method swap <t>, the C # compiler automatically converts the defined generic type to the type specified in the reference code, this greatly simplifies the coding workload of programmers.

Because the generic <t> can represent any type, only one parameter type of the method can be defined to reference all types. For example, D1 in Example 6 may be of the Int or float type (D2 is the same). If the generic type is not used, many overloaded swap methods need to be written to make the code bloated, it is not easy to read, but also increases the compilation workload. From this we can see that the advantages of generics are obvious.

 

Common generic set

In the. NET Framework class library, the system. Collections. Generic and system. Collections. objectmodel Namespaces provide many generic collection classes. Many generic set types are directly simulated by generic types. Table 1 lists the mappings between common generic collection classes and non-generic collection classes.

Table 1 common generic collection classes and their corresponding non-generic collection classes

1. List <t>

A list generic class indicates a list of strong types of objects that can be accessed through an index. It provides methods for searching, sorting, and operating the list. The common method is as follows.

Add method: add the element of the specified value to list <>.

Insert method: Insert a new element in the middle of the list.

Contains method: test whether an element exists in the list.

Remove Method: remove an element with a specified key from the list.

Clear: removes all elements from the list.

2. dictionary <tkey, tvalue>

The dictionary generic class provides a set of key-to-value ing. Each added item in the dictionary is composed of a value and its associated keys, which are retrieved by keys. The common method is as follows:

Add method: add elements with specified keys and values to dictionary <,>.

Trygetvalue: gets the value associated with the specified key.

Containskey method: determines the dictionary <,> to remove the element with the specified key.

Remove Method: remove an element with the specified key from dictionary.

3. Queue <t>

The queue generic class indicates the object's first-in-first-out set.

The common method is as follows:

Enqueue method: inserts a specified element into the end of a column.

Dequeue method: the first element of the queue is listed.

4. Stack <t>

The stack generic class indicates the variable size of an instance of any type, and then the first-in-first-out (LIFO) set.

The common method is as follows:

Push method: inserts a specified element into the stack.

Pop method: pop up the stack item element.

5. sortedlist <tkey, tvalue>

Sortedlist generic classes represent the set of key/value pairs. These key/value pairs are sorted by key based on the associated icomparer.

The common method is as follows:

Add method: add elements with specified keys and values to sortedlist <,>.

Trygetvalue: gets the value associated with the specified key.

Containskey method: Determine whether sortedlist <,> contains the specified key.

Remove Method: remove an element with the specified key from sortedlist <,>.

 

Example 5: There is a current account of the Current Account type. There is a createaccount (account name, account amount) method for the customers class that provides services for it. Try using sortedlist <,> create a generic object and determine whether there is an account named "Zhang San". If no, create an account. If yes, append a deposit to the account.

The main code is as follows:

Code

  1   Using  System;
2 Using System. IO;
3 Using System. Collections. Generic;
4 Namespace Genricexample
5 {
6 Public Class Account
7 {
8 Private String Accountname;
9 Private Int Accountvalue;
10 Public String Accountname
11 {
12 Get
13 {
14 Return Accountname;
15 }
16 Set
17 {
18 Accountname = Value;
19 }
20 }
21 Public Int Accountvalue
22 {
23 Get
24 {
25 Return Accountvalue;
26 }
27 Set
28 {
29 Accountvalue = Value;
30 }
31 }
32 }
33 Public Class MERs
34 {
35 Public Void Createaccount ( String Name, Int Value1)
36 {
37 Account ACC = New Account ();
38 ACC. accountname = Name;
39 ACC. accountvalue = Value1;
40 }
41 }
42 Class Porgram
43 {
44 Static Void Main ( String [] ARGs)
45 {
46 Sortedlist < String , Account > Accounts = New Sortedlist < String , Account > ();
47 MERs Customs = New MERs ();
48 If (Accounts. containskey ( " AA " ) = False )
49 {
50 // If this account does not exist, create an account and use the deposit as the account opening amount
51 Account account = New Account ();
52 Customs. createaccount ( " Zhang San " , 1000 );
53 Accounts. Add ( " Zhang San " , Account );
54 }
55 Else
56 {
57 // If you have this account, add a deposit to the existing account
58 Account account = Accounts [ " Zhang San " ];
59 // Account append deposits
60 }
61 }
62 }
63 }
64

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.