Generic (generic), Generic generic

Source: Internet
Author: User

Generic (generic), Generic generic

Generic is a new feature of C # Language 2.0 and general language runtime (CLR. The generic. NET Framework introduces the concept of type parameters. Type parameters make it unnecessary to determine one or more specific parameters when designing classes and methods. The specific parameters can be declared and implemented in the Customer Code. This means that the generic type parameter T is used to write a class MyList <T>. The customer code can call: MyList <int>, MyList <string> or MyList <MyClass>. This avoids the cost and risks of type conversion or packing during running.

When the generic type does not appear, when we output the int type value:

When the string type value is output:

When outputting values of the DateTime type:

... Output A write method. This is the most primitive method, and the performance is the highest. However, we strive for perfection in development!

Later, the majority of our working people came up with a solution, that is, the crystallization of the wisdom of the working people in the. net framework 1.1 era, to provide a ShowObject (object oParameter) method.

1 introduce generic: latency statement

This method also has a problem, that is, when the value type is passed, for example, the int type, it involves packing when the value type is converted to the reference type. during use, unpacking is involved when this reference type is converted to a value type again. If you want to pursue performance, you will be concerned about this issue! It also involves that the attribute values cannot be accessed, and there is another type security problem! Therefore, Microsoft has proposed a new solution-Generic)

2. How to declare and use generics:

3 benefits and principles of generics

Generics are intended to be reused when we have the same content or operations but different types of parameters passed!

4. generic classes, generic methods, generic interfaces, and generic delegation

Generics are used in four places: generic methods, generic classes, generic interfaces, and generic delegation.

Generics are easy to write. The following describes some of the troubles in generics: inheritance of generic classes and interface implementation problems.

5 generic Constraints

These five constraints can be used together! Base class constraints, interface constraints, reference type constraints, value type constraints, no parameter constructor constraints!

6. covariant Inverter

Referenced in. net framework3.5 in C #4.0!

1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. text; 5 using System. threading. tasks; 6 7 namespace MyGeneric. extend 8 {9 /// <summary> 10 // The value can only be placed before the interface or the delegated generic parameter. 11 // out covariant modifies the return value. 12 // in inversion contravariant modifier passed in parameter 13 /// </summary> 14 public class CCTest 15 {16 public static void Show () 17 {18 // IEnumerable <int> 19 // Action <int> act = null; 20 {2 1 Bird bird1 = new Bird (); 22 Bird bird2 = new Sparrow (); // element Bird and Sparrow have an inheritance relationship, so you can point to the subclass. No problem! 23 Sparrow sparrow1 = new Sparrow (); 24 // Sparrow sparrow2 = new Bird (); 25} 26 27 {28 // List <int> intList = new List <int> (); 29 List <Bird> birdList1 = new List <Bird> (); 30 31 // List <Bird> birdList2 = new List <Sparrow> (); // List <Bird> and List <Sparrow> are not parent-child relationships, there is no inheritance relationship 32 // a group of sparrows must be a group of birds who can understand the above, but the program does not understand this logic, the program only recognizes the inheritance relationship, and the List <Bird> and List <Sparrow> do not have the inheritance relationship. Therefore, it cannot pass 33 34 List <Bird> birdList3 = new List <Sparrow> (). select (c => (Bird) c ). toList (); 35} 36 37 {// covariant 38 IEnumerable <Bird> birdList1 = new List <Bird> (); 39 40 IEnumerable <Bird> birdList2 = new List <Sparrow> (); // It is changed to allow the program to identify this situation. For convenience, the type conversion is reduced, avoid the problem of rigid compiler conversion. This is because Microsoft forgot this requirement when launching the generic model, the generic parent class can point to the generic subclass 41 // a group of sparrows must be a group of birds 42 43 Func <Bird> func = new Func <Sparrow> () => null ); 44 45 ICustomerListOut <Bird> customerList1 = new CustomerListOut <Bird> (); 46 ICustomerListOut <Bird> customerList2 = new CustomerListOut <Sparrow> (); 47} 48 49 50 51 {// inverter 52 ICustomerListIn <Sparrow> customerList2 = new CustomerListIn <Sparrow> (); 53 ICustomerListIn <Sparrow> customerList1 = new CustomerListIn <Bird> (); 54 55 ICustomerListIn <Bird> birdList1 = new CustomerListIn <Bird> (); 56 birdList1.Show (new Sparrow (); 57 birdList1.Show (new Bird ()); 58 59 Action <Sparrow> act = new Action <Bird> (Bird I) =>{}); 60} 61 62 63 {64 IMyList <Sparrow, bird> myList1 = new MyList <Sparrow, Bird> (); 65 IMyList <Sparrow, Bird> myList2 = new MyList <Sparrow, Sparrow> (); // synced change 66 IMyList <Sparrow, Bird> myList3 = new MyList <Bird, Bird> (); // inverter 67 IMyList <Sparrow, Bird> myList4 = new MyList <Bird, sparrow> (); // covariant + inverter 68 69 // Func <string, long> 70} 71} 72} 73 74 // <summary> 75 // Bird 76 // </summary> 77 public class Bird 78 {79 public int Id {get; set;} 80} 81 // <summary> 82 // Sparrow 83 // </summary> 84 public class Sparrow: Bird 85 {86 public string Name {get; set ;} 87} 88 89 90 91 92 93 // <summary> 94 // inverter 95 /// </summary> 96 /// <typeparam name = "T"> </typeparam> 97 public interface ICustomerListIn <in T> 98 {99 // T Get (); // It cannot be returned. It can only be used as a parameter to pass 100 101 void Show (T t); 102} 103 104 public class CustomerListIn <T>: ICustomerListIn <T> 105 {106 // public T Get () 107 // {108 // return default (T); 109 //} 110 111 public void Show (T t) 112 {113} 114 115 116 // <summary> 117 // The output result can only be 118 /// </summary> 119 // <typeparam name = "T"> </typeparam> 120 public interface ICustomerListOut <out T> 121 {122 T Get (); 123 124 // void Show (T t ); // T cannot be used as input parameter 125} 126 127 // <summary> 128 // class no covariant inverter 129 // </summary> 130 // <typeparam name = "T"> </typeparam> 131 public class CustomerListOut <T>: ICustomerListOut <T> 132 {133 public T Get () 134 {135 return default (T); 136} 137 138 // public void Show (T t) 139 // {140 141 142 //} 143 144 145 146 147 148 149 public interface IMyList <in inT, out outT> 150 {void Show (inT t ); 151 outT Get (); 152 outT Do (inT t); 153 154 // out can only be returned. in can only be 155 // void Show1 (outT t ); 156 // inT Get1 (); 157 158} 159 160 public class MyList <T1, T2>: IMyList <T1, T2> 161 {162 163 public void Show (T1 t) 164 {165 Console. writeLine (t. getType (). name); 166} 167 168 public T2 Get () 169 {170 Console. writeLine (typeof (T2 ). name); 171 return default (T2); 172} 173 174 public T2 Do (T1 t) 175 {176 Console. writeLine (t. getType (). name); 177 Console. writeLine (typeof (T2 ). name); 178 return default (T2); 179} 180} 181 182}
View Code

Func <string, long> in this way, the covariant and inverter are used!

7. Generic Cache

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; using System. threading. tasks; namespace MyGeneric. extend {public class GenericCacheTest {public static void Show () {// use the static dictionary and read it in the dictionary! All are global for (int I = 0; I <5; I ++) {Console. writeLine (DictionaryCache. getCache <int> (); Thread. sleep (10); Console. writeLine (DictionaryCache. getCache <long> (); Thread. sleep (10); Console. writeLine (DictionaryCache. getCache <DateTime> (); Thread. sleep (10); Console. writeLine (DictionaryCache. getCache <string> (); Thread. sleep (10); Console. writeLine (DictionaryCache. getCache <GenericCacheTest> (); Thread. lupus Ep (10);} // The generic cache is global for (int I = 0; I <5; I ++) {Console. writeLine (GenericCache <int>. getCache (); Thread. sleep (10); Console. writeLine (GenericCache <long>. getCache (); Thread. sleep (10); Console. writeLine (GenericCache <DateTime>. getCache (); Thread. sleep (10); Console. writeLine (GenericCache <string>. getCache (); Thread. sleep (10); Console. writeLine (GenericCache <GenericCacheTest>. getCache (); Threa D. sleep (10) ;}}/// <summary> /// a method for caching frequently /// dictionary cache: static attribute resident memory // </summary> public class DictionaryCache {private static Dictionary <string, string> _ TypeTimeDictionary = null; static DictionaryCache () {Console. writeLine ("This is DictionaryCache static constructor"); _ TypeTimeDictionary = new Dictionary <string, string> ();} public static string GetCache <T> () {Type type = typeof (T); if (! _ TypeTimeDictionary. containsKey (type. name) {_ TypeTimeDictionary [type. name] = string. format ("{0 }_{ 1}", typeof (T ). fullName, DateTime. now. toString ("yyyyMMddHHmmss. fff ");} return _ TypeTimeDictionary [type. name] ;}/// <summary> // a different copy is generated for each different T to solve specific scenarios and save fixed data, such: configuration file and configuration item in the program! /// Suitable for different types of scenarios where one copy of data needs to be cached, which is efficient and fast! Take it directly next to the cup (Benefit) /// cannot be cleared /// </summary> /// <typeparam name = "T"> </typeparam> public class GenericCache <T> {static GenericCache () {Console. writeLine ("This is GenericCache static constructor"); _ TypeTime = string. format ("{0 }_{ 1}", typeof (T ). fullName, DateTime. now. toString ("yyyyMMddHHmmss. fff ");} private static string _ TypeTime =" "; public static string GetCache () {return _ TypeTime ;}}}
View Code

 

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.