C# Notes - 3. Generics

Introduction to Generics:

The introduction of C# 2.0 generic mechanism realizes the parameterization of types and methods, that is, types become parameters to achieve logical reuse, and a large number of type safety checks are transferred from runtime to compile time, which improves the speed of code running.
Advantages of generics:
1) Type safety
When we use generic types or generic methods to operate on a specific data type, the compiler will ensure that these generic types or generic methods are only applicable to objects compatible with the data type , otherwise, the compiler will report an error.

2) Improve performance

If there is no generic mechanism, we need to use the object type as a parameter or return value type, so we need to perform forced type conversion; when the object we operate is a value type, we will need boxing and unboxing operations. . After the introduction of the generic mechanism, we can manipulate types by creating generic types or generic methods, so there is no need for coercion, type safety checking at runtime, and no need to perform boxing, unboxing, and promotion when manipulating value types. code performance

generic type

The generic mechanism provided by the C# language is mainly divided into two forms:
generic types (including: generic classes, generic interfaces, generic delegates, and generic structures) and generic methods.

Internal implementation mechanism of
generic type: After the type parameter of the generic type is specified,
1) When JIT compiles the code using the generic type parameter, the runtime will first obtain its corresponding CIL code;
2) Use The specified type arguments are replaced;
3) Finally, the replaced CIL code is compiled into native code

generic interface

Generic interfaces prevent boxing that might arise when manipulating value types with non-generic interfaces, and provide compile-time type safety.

generic delegate

generic method

Type Constraints and Type Inference in Generics

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325066874&siteId=291194637