Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Generic is a new feature of the C# language 2.0 and the common language runtime (CLR). NET framework introduced the concept of type parameters so that when designing classes and methods, it is not necessary to determine one or more specific parameters, the specific parameters can be delayed to the client code declaration, implementation.
Definition of generic methods
Some of the code uses c# 7.0 syntax
Public List<T> Method<T>() => new List<T>(); Public string method<T>(T T)=> ";Copy the code
The definition of generic interfaces
Public interface CustomCollection<T>{}Copy the code
The definition of generic classes
Public class CustomClass<T>{}Copy the code
Definition of generic delegate
Public Action<T> act = null; Public Func<T> fuc = null;Copy the code
-
The default keyword in generic code
1.T will be a value type or a reference type.
2. If T is a value type, then T will be numeric or structural.
3. If T is a reference type T=null, T=0 is valid for numeric types, but not for structs.
4. Return zero for the value type, or 0 or NULL depending on the type of the structure member.
Types and characteristics of generic constraints
1. Base class constraints
2. Interface constraints
3. Type constraints
4. Value type constraints
5. No-parameter constructor constraint
1. Bring the power to use properties and methods in the base class. 2. The type parameter must be a base class or a subclass of it. 3. Several type constraints on generics are And relationships.
Public class C1 {public int Id {get; set; } public string Name { get; set; }} public static void Method<T>(T T) where T: <T T>(T T); C1,new() { t.Id(); T t = new T(); }Copy the code
Contravariant and covariant of generics
Public class Test {/// <summary> // parent class A /// </summary> public class A {} // <summary> // subclass B // </summary> public class B:A { } A a1 = new A(); B1 = new B(); A a2 = new B(); List<A> _list = new List<A>(); // Cannot create instance because it is A new type List<A> type, List<B> type List<A> _bList = new List<B>(); IEnumerable<A> a_list = new List<B>(); IEnumerable<B> a_list = new List<A>(); } 1, List<A> _bList = new List<B>() </br> 2, List<B> _bList = new List<A>() Decorates the return value to indicate that T can only be used as a return value in a type. </br> 4, in inverter: modifies the parameter, indicating that T can only be used as a parameter in the type. </br> 5, can only be placed in front of interface or delegate generic parameters. </br>Copy the code
Generic caching
1. Generic class static field, is independent, can be implemented cache (in memory, using static constructor or static field implementation)
2. Generic caching can be implemented for different types
Public class GenericCache<T> {static GenericCache() {_TypeTime = string.format ("{0}_{1}", typeof(T).FullName, DateTime.Now.ToString("yyyyMMddHHmmss.fff")); } private static string _TypeTime = ""; public static void GetCache() { console.writeLine(_TypeTime); For (int I = 0; int I = 0; int I = 0; i < 5; i++) { GenericCache<int>.GetCache(); Thread.Sleep(10); GenericCache<long>.GetCache(); Thread.Sleep(10); GenericCache<DateTime>.GetCache(); Thread.Sleep(10); GenericCache<string>.GetCache(); Thread.Sleep(10); GenericCache<GenericCacheTest>.GetCache(); Thread.Sleep(10); }Copy the code
The advantages of generics
1. Lazy loading can be realized, which is generated by the process of.NET compilation.
2. Performance safety, eliminating the packing and unpacking caused by forced conversion.
The implementation principle of generics. NetFarmWork compilation
1. The vs compiler compiles C# code to exe or DLL (generating IL and metadata).
2. Exe and DLL will be compiled into machine code by THE JIT in CLR and executed by CPU.
3. The language upgrade is compatible with “<>”. The compiler upgrade recognizes “<>” and compiles “<>” into placeholders in IL, which can be seen through decompiler software after the first compilation of IL code (‘ 1 represents one parameter ‘2 represents two parameters).
4. JIT JIT compilation will compile to the original type according to the type specified by the caller.
5. The same generic type, passing different parameters, after the JIT secondary compilation will become different types.
6. Static fields/static constructors are initialized only once and reside in memory.
Why object as a parameter is evil?
1. First, due to the conversion of packing and unpacking, there will be a certain loss in performance
2. Second due to the characteristics of c# itself,Obejct is the base class of all types, so all concrete types as parameters can be used instead of Object, but it is not safe, will cause some code compiled without error, error execution.