Talk to Xiaojing to read CLR via C # (16)-generic

Source: Internet
Author: User

Generic is like a template, which often defines some commonAlgorithmTo replace the data type with the actual data type during the call.CodeIs reusable.

I. general 1. Simple Example

Take the generic list in the most common FCL as an example:

Static void main (string [] ARGs)
{
List <int> num = new list <int> ();
Num. Add (1 );
Num. Add (3 );
Int num1 = num [0];
Int num2 = num [1];
}

T in angle brackets is an uncertain data type, which is called a type parameter. Generally, it must start with a letter T, which can be tkey or tvalue. The specific type specified during the call is called the type real parameter.

Check the Il code:

    • The type name list ends with "'" and a number. A number indicates the number of elements of a type, that is, the number of parameters of a specific type.
    • Generic is type-safe. If "num. Add (" A ");" is used, a compilation error occurs;
    • The generic type can improve the reusability of the algorithm. In addition, the int type is not used for packing and unpacking, Which is improved compared to converting all types into objects.ProgramPerformance.
    • It is often used to set default values for generic variables.DefaultKeyword, t temp = default (t ). If T is a reference type, temp is null. If T is a value type, temp is set to 0.
2. Open and closed types:

Open type: the type with generic parameters is open type, such as list <t>. CLR does not allow the construction of Open Type instances;

Closed Type: when calling the Code, if the actual data type has been specified for all type arguments, such as list <string>, this type is closed. CLR allows the construction of closed instances.

3. type inference:

Let's take a look at this common code:

To enhance readability, the compiler supports the type inference function. If you omit <>, you can change the method called above:

*Note that C # uses the data type of the variable during type inference, rather than the type of the object referenced by the variable. For example:

Although S1 and S2 both point to string objects, the types of these two variables are different, so compilation errors may occur.

Ii. Generic parameters of the covariant and Inverter

You can convert the type parameters of the generic delegate or interface to a certain extent by using the co-variables and the amount of inverters.

    • Inverter quantity: Generic parameters can be converted from the base class to the derived class. They are identified by the In keyword and only appear at the input position, such as the parameters of the method;

Public Delegate void func <in T> (T Arg );

Static void main (string [] ARGs)

{

Func <Object> F1 = NULL;

Func <string> F2 = F1;

}

    • Co-variable: a generic type parameter can be changed from a derived class to its base class. It is identified by the out keyword and only appears at the output position, such as the return value of a method.

Public Delegate tresult func <out tresult> ();

Static void main (string [] ARGs)

{

Func <string> fn = NULL;

Object result = FN ();

}

Iii. Generic Constraints

When designing generic type parameters, you can use the WHERE clause to specify the constraints that the type must meet. It mainly includes the following constraints:

1. Main constraints

A type parameter can specify 0 or 1 primary constraint. The primary constraint can be an unsealed reference type, which indicates that the type of the real parameter must be the same as the constraint type or be a derived class of the constraint type. The reference type cannot be object, array, Delegate, multicastdelegate, valuetype, Enum, or void.

Class constraint1 <t> where T: Stream
{
Public void close (T Stream)
{
Stream. Close ();
}
}

Class Program
{
Static void main (string [] ARGs)
{
Constraint1 <filestream> S2 = new constraint1 <filestream> ();
}
}

There are two special constraints: class and struct.

    • Class constraint: the specified type real parameter must be of the reference type. Where T: Class

Without any constraints, if T is of the value type, the value cannot be null. Therefore, a compilation error occurs. After adding constraints, the compilation passes:

    • Struct constraint: the specified type of real parameter must be a value type.

Without any constraints, if T is of the reference type, it cannot be declared as a null value, so a compilation error occurs. After the struct constraint is added, it runs normally:

2. Secondary Constraints

A type parameter can specify 0 or multiple secondary constraints. There are two common secondary constraints:

    • Interface constraints: All specified interfaces must be implemented for type parameters. For example:

Another advantage of interface constraints is that value-type real parameters do not need to be boxed when calling interface methods.

    • Type parameter constraints: there is a certain relationship between the specified type parameters. For example, an inheritance relationship is required:

3. constructor Constraints

The constructor constraint requires that the type real parameters must implement the non-argument constructor, and it does not support the parameter constructor.

 

You may like:Reading CLR via C # (00) with Xiaojing-opening part and Directory

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.