C# knowledge generic paradigm
        Generics are 2.0 edition C# Language and common language runtime (CLR) A new feature in . Generics introduce the concept of type parameters .NET
Framework, Type parameters make it possible to design the following classes and methods : These classes and methods defer the designation of one or more types until the client code declares and instantiates the class or method . for example , By using generic type parameters
T, You can write a single class that other client code can use , Without introducing the cost or risk of runtime cast or boxing operations , Avoiding the need for cast and improving type security .

Overview and advantages of generics
        Both generic classes and generic methods are reusable , Type safety and high efficiency . It is usually used in collections and methods running on collections ..NET
2.0 A new class library named System.Collections.Generic Namespace for , It contains several new generic based collection classes .        
You can also create custom generic types and methods .         Generic class and method reception ” Type parameter “, Specifies the type of object to operate on : public class Test<T> {} 
      Type is specified only when instantiated . Test<int> tree = new Test<int>();         Using generic types has the following advantages :
* Use generic types to maximize code reuse , Protect the type of security and improve performance .
* The most common use of generics is to create collection classes .
* .NET Framework Class library in System.Collections.Generic
The namespace contains several new generic collection classes . Use these classes as much as possible in place of ordinary classes , as System.Collections In the namespace ArrayList.
* You can create your own generic interfaces , Generic class , generic method , Generic events and generic delegates .
* Generic classes can be constrained to access methods of specific data types .
* Information about the types used in generic data types can be obtained at run time through reflection .
Type parameters in generics T
        Type parameter T A place holder for defining a generic class , It's not a type , Represents only one possible type . At the time of definition ,T The position that appears can be replaced by any type in use .

Deciding when and where to use generics
        There are several things you need to consider : 
*
Does the type you are using contain or operate on an unspecified data type ( Such as set type )? If so , Creating generic types will provide more benefits . If your type only operates on a single specified type , There is no need to create a generic class . 
* If your type will operate on value types , Then there will be boxing and unpacking operations , You should consider using generics to prevent boxing and unpacking operations . 
* Strong type checking of generics helps to find errors quickly ( That is, compile time, not run time ), So as to shorten the time bug Repair cycle .
*
When writing multiple classes to operate on multiple data types “ Code inflation ” problem ( Like a ArrayList Store only StreamReaders And another store StreamWriters)? It's very simple to write code once and make it work on multiple data types .
* Generics make code clearer . By eliminating code bloat and performing mandatory checks , Your code will become easier to read and understand .
Generics for classes
        For different types of arrays , Write an array specific ” Bubble sort “.
thinking

* Generics for classes , Generics are typed next to classes .
* Due to the ” Bubble sort “ You need to compare elements in , So generics are constrained to implementation IComparable Interface .namespace ConsoleApplication1 {
class Program { static void Main(string[] args) { SortHelper<int> isorter = new
SortHelper<int>(); int[] iarray = { 8, 7, 1, 2, 12 };
isorter.BubbleSort(iarray); foreach (int item in iarray) { Console.Write(item +
","); } Console.ReadKey(); } } public class SortHelper<T> where T : IComparable
{ public void BubbleSort(T[] array) { int length = array.Length; for (int i =
0; i <= length - 2; i++) { for (int j = length - 1; j >= 1; j--) { if
(array[j].CompareTo(array[j - 1]) < 0) { T temp = array[j]; array[j] = array[j
- 1]; array[j - 1] = temp; } } } } } }        output :

On generic constraints

* where T : IComparable hold T Constraints for implementation IComparable Interface  
* where T : class 
* where T : struct 
* where T : IComparable, new() Constraint generics must have constructors
On Bubble algorithm

* reason why for (int i = 0; i <= length -2;
i++), This is boundary thinking , For example, there is a length of 5 Array of , If 0 Finally, the sign element is changed to 4 Sign position , Adjust one bit at a time , Need to go through 4 Time to arrive 4 Sign position , Namely for(int i = 0; i
<= 5-2, i++),i The order is as follows 0, 1, 2, 4, During this period, I experienced 4 second .
* as for for (int j = length - 1; j >= 1;
j--) loop , That is, the traversal starts from the last element until the index is 1 Elements of , Compare each time with the element in the previous position .
On comparison
        int Why types can be compared , Because int Type implements IComparable Interface .byte The same is true of the type .
Customize a class , It can also realize bubble algorithm
        Bubble algorithm involves element comparison , So the custom class must be implemented IComparable Interface . namespace ConsoleApplication1 {
class Program { static void Main(string[] args) { Book[] bookArray = new
Book[2]; Book book1 = new Book(100, " Book one "); Book book2 = new Book(80, " Book 2 ");
bookArray[0] = book1; bookArray[1] = book2; Console.WriteLine(" Before bubbling :"); foreach
(Book b in bookArray) { Console.WriteLine(" title :{0}, Price :{1}", b.Title, b.Price); }
SortHelper<Book> sorter = new SortHelper<Book>(); sorter.BubbleSort(bookArray);
Console.WriteLine(" After bubbling :"); foreach (Book b in bookArray) {
Console.WriteLine(" title :{0}, Price :{1}", b.Title, b.Price); } Console.ReadKey(); } }
public class SortHelper<T> where T : IComparable { public void BubbleSort(T[]
array) { int length = array.Length; for (int i = 0; i <= length - 2; i++) { for
(int j = length - 1; j >= 1; j--) { if (array[j].CompareTo(array[j - 1]) < 0) {
T temp = array[j]; array[j] = array[j - 1]; array[j - 1] = temp; } } } } }
// Custom implementation IComparable Interface public class Book : IComparable { private int price;
private string title; public Book(){ } public Book(int price, string title) {
this.price = price; this.title = title; } public int Price { get { return
this.price; } } public string Title { get { return this.title; } } public int
CompareTo(object obj) { Book book = (Book)obj; return
this.Price.CompareTo(book.Price); } } }        output :

Methods for generics
        Continue with the example above , Customize a class , And define generic methods . namespace ConsoleApplication1 { // Method generics public
class MethodSortHelper { public void BubbleSort<T>(T[] array) where T :
IComparable { int length = array.Length; for (int i = 0; i <= length - 2; i++)
{ for (int j = length - 1; j >= 1; j--) { if (array[j].CompareTo(array[j - 1])
< 0) { T temp = array[j]; array[j] = array[j - 1]; array[j - 1] = temp; } } } }
} }        The main program is as follows : namespace ConsoleApplication1 { class Program { static void
Main(string[] args) { Book[] bookArray = new Book[2]; Book book1 = new
Book(100, " Book one "); Book book2 = new Book(80, " Book 2 "); bookArray[0] = book1;
bookArray[1] = book2; Console.WriteLine(" Before bubbling :"); foreach (Book b in bookArray)
{ Console.WriteLine(" title :{0}, Price :{1}", b.Title, b.Price); } MethodSortHelper
sorter = new MethodSortHelper(); sorter.BubbleSort<Book>(bookArray);
Console.WriteLine(" After bubbling :"); foreach (Book b in bookArray) {
Console.WriteLine(" title :{0}, Price :{1}", b.Title, b.Price); } Console.ReadKey(); } }
// Custom implementation IComparable Interface public class Book : IComparable { private int price;
private string title; public Book() { } public Book(int price, string title) {
this.price = price; this.title = title; } public int Price { get { return
this.price; } } public string Title { get { return this.title; } } public int
CompareTo(object obj) { Book book = (Book)obj; return
this.Price.CompareTo(book.Price); } } }        output :
        When using generic methods , Except for that : MethodSortHelper sorter = new MethodSortHelper();
sorter.BubbleSort<Book>(bookArray);        You can write it like this : MethodSortHelper sorter =
new MethodSortHelper(); sorter.BubbleSort(bookArray);       
so , The generic method can implicitly infer whether a generic satisfies the condition based on the data instance .

Other advantages of generics

Avoid implicit packing and unpacking
        The following includes implicit packing and unpacking : ArrayList list = new ArrayList(); for(int i = 0; i < 3;
i++) { list.Add(i); //Add The parameter type received is a reference type object, Implicit packing is included here } for(int i = 0; i < 3;
i++) { int value = (int)list[i]; // Strong conversion of reference type to value type , Unpacking Console.WriteLine(value); }   
    Use generics to avoid implicit boxing and unpacking : List<int> list = new List<int>(); for(int i = 0; i < 3; i++)
{ list.Add(i); } for(int i = 0; i < 3; i++) { int value = list[i];
Console.WriteLine(value); }
Be able to detect errors in time during compilation
        Do not use generics , An example of not reporting errors during compilation : List<int> list = new List<int>(); for(int i = 0;
i < 3; i++) { list.Add(i); } for(int i = 0; i < 3; i++) { int value = list[i];
Console.WriteLine(value); }        Use Generics , Errors are found in time during compilation : List<int> list = new
List<int>(); int i = 100; list.Add(i); string value = (string)list[0];
Tips for using generics

Alias generics in the current file
using IntList = List<int>; IntList list = new IntList(); list.Add(1);
Using generic aliases in different files , Defining a class derives from generics
public class IntList : List<int>{}

Technology
©2019-2020 Toolsou All rights reserved,
MySql sentence Recursively find all subordinate departments of an input department Android 11 Official release !【Python】 read txt file , Gets the specified location data in the specified row subversion ! Never take a nap longer than this time ! Watch out for fatal diseases … use PyMC3 Bayesian statistical analysis was performed ( code + example )【JAVA】【 Huawei campus recruitment written examination - Software 】2020-09-09( Essence )2020 year 7 month 15 day Wechat applet template Use of python obtain excel A column or row of data mybatis Return result mapping of series [AndroidO] [RK3399] -- GPIO Drive and control mode