C # reference: generics (2)-What is generics? Generic implementation? What are the benefits of generics?

Source: Internet
Author: User
Tags microsoft c
What is generics?

You can define a type security class through the generic type without compromising the type security, performance, or work efficiency.
You only need to implement the server as a general server at a time, and can declare and use it in any type.
To do this, you need to use <And >Parentheses to enclose general type parameters.

For example, you can define and use a general Stack as follows: public class Stack
{
T [] m_Items;
Public void Push (T item)
{}
Public T Pop ()
{}
}
Stack stack = new Stack ();
Stack. Push (1 );
Stack. Push (2 );
Int number = stack. Pop ();

Code Block 2Shows the complete implementation of a general stack.
SetCode Block 1(Part 1 "Introduction to C # generics") andCode Block 2For comparison, you will see, as ifCode Block 1InCode Block 2Are replaced with T, except that the general type parameter T is used to define the Stack: public class Stack
{}

When using a general stack, you must notify the compiler of the type used to replace the general type parameter T (whether when declaring a variable or instantiating a variable ): stack stack = new Stack ();

The compiler and Runtime Library are responsible for completing other work. All methods (or attributes) that accept or return T will be changed to use the specified type (integer in the preceding example ).
Code Block 2. General Stack

Public class Stack
{
Readonly int m_Size;
Int m_StackPointer = 0;
T [] m_Items;
Public Stack (): this (100)
{}
Public Stack (int size)
{
M_Size = size;
M_Items = new T [m_Size];
}
Public void Push (T item)
{
If (m_StackPointer> = m_Size)
Throw new StackOverflowException ();
M_Items [m_StackPointer] = item;
M_StackPointer ++;
}
Public T Pop ()
{
M_StackPointer --;
If (m_StackPointer> = 0)
{
Return m_Items [m_StackPointer];
}
Else
{
M_StackPointer = 0;
Throw new InvalidOperationException ("Cannot pop an empty stack ");
}
}
}

NoteT is a common type parameter (or type parameter), and the general type is Stack. Int in Stack is a type real parameter.
The advantage of this programming model is that internal algorithms and data operations remain unchanged, and the actual data type can be changed by using the server code on the client.

Generic implementation:

On the surface, the C # Generic syntax looks similar to the C ++ template, but there are significant differences in how the compiler implements and supports them. As you will see later, this is of great significance for generic usage.

NoteIn this article, when C ++ is mentioned, it refers to traditional C ++, rather than Microsoft C ++ with managed extensions.

Compared with the C ++ template, the C # Generic Model provides enhanced security, but is also limited in terms of functionality.

In some C ++ compilers, the compiler does not even compile template code until you use a template class of a specific type. When you specify a type, the compiler inserts code in inline mode and replaces each common type parameter with the specified type. In addition, whenever you use a specific type, the compiler inserts code specific to this type, regardless of whether you have specified this type for the template class elsewhere in the application. The C ++ linker is responsible for solving this problem and is not always valid. This may cause code expansion and increase the loading time and memory footprint.

In. NET 2.0, generics are supported locally in IL (intermediate language) and CLR itself. When compiling General C # server-side code, the compiler will compile it into IL, just like any other type. However, IL only contains parameters or placeholders of specific types. In addition, the metadata of the general server contains general information.

The client compiler uses this general metadata to support type security. When the client provides a specific type parameter instead of a general type parameter, the client compiler replaces the general type parameter in the server metadata with the specified type parameter. This will provide the client compiler with type-specific server definitions, as if they were never involved in generics. In this way, the client compiler can ensure the correctness of method parameters, implement type security checks, and even execute type-specific intelliisense.

The interesting question is how. NET compiles the General IL of the server into machine code. Originally, the actual machine code generated depends on whether the specified type is a value type or a reference type. If the client specifies a value type, the JIT compiler replaces the general type parameter in IL with a specific value type and compiles it into local code. However, the JIT compiler tracks the server code of the type it has generated. If the JIT compiler is requested to compile a general server with the value type that has already been compiled as the machine code, it only returns a reference to the server code. The JIT compiler will use server code of the same value type in all future scenarios, so there is no code expansion problem.

If the client specifies the reference type, the JIT compiler replaces the common parameter in server IL With the Object and compiles it into the local code. This code will be used in any future requests for reference types rather than general type parameters. Note that, in this way, the JIT compiler only re-uses the actual code. The instance still allocates space based on the size of the heap they leave, and there is no forced type conversion.
 
Benefits of generics:
Generic in. NET allows you to reuse code and make efforts to implement it. Type and internal data can be changed without causing code expansion, regardless of whether you are using a value type or a reference type. You can develop, test, and deploy code at one time, reuse it by any type (including future types), and all have compiler support and type security. Because the General Code does not forcibly pack or unpack the value type, or forcibly convert the reference type downward, the performance is significantly improved. For value types, the performance is generally increased by 200%. For reference types, the performance can be expected to be increased by up to 100% when accessing this type (of course, the performance of the entire application may be improved, it may not improve ). The source code included in this article contains a micro-benchmark application that executes stacks in a tight loop. This application allows you to test the value type and reference type on the Object-based stack and general stack, and change the number of iterations to view the impact of generics on performance.

Related Article

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.