Introduction to generics

Source: Internet
Author: User
Value type conversion to reference type isPacking, Exist on the stack
Conversion of reference type to value type isUnpack, Exist on the stack

GenericUse oneData Type TTo replace the object, specify the T type during class instantiation, and automatically compile the runtime as local code, which greatly improves the running efficiency and code quality,
And ensures data type security.

Public class Stack <t>

{

Private T [] m_item;

Public t POP (){...}

Public void push (T item ){...}

Public stack (int I)

{

This. m_item = new T [I];

}

}

Instantiation:

Stack <int> A = new stack <int> (100 );

A. Push (10 );

A. Push ("8888"); // This row is not compiled because Class A only receives int-type data.

Int x = A. Pop ();

 

1. It is type-safe. If a stack of the int type is instantiated, data of the string type cannot be processed. The same applies to other data types.

2. No packing or folding is required. This class generates local code according to the input data type during instantiation. The data type of the local code has been determined, so there is no need to pack or fold the box.

3. No type conversion is required.

 

 

C # has two types of data:Reference Type and Value Type. Reference types such as all classes. value types are generally the most basic types of languages, such as int, long, and struct. In the constraints of generics, we can also limit the type T to be a reference type or a value type in a wide range. The corresponding keywords are class and struct:

Public class node <t, V> where T: Class

Where V: struct

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.