C # knowledge generics

Source: Internet
Author: User

C # knowledge generics
C # knowledge generics are a new feature in C #2.0 and CLR. 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 delay one or more types until the client Code declares and instantiate the class or method. For example, by using the generic type parameter T, you can write a single class that can be used by other client code without introducing the cost or risk of force conversion or packing during runtime, avoid the need for forced type conversion to improve type security.
Generic overview and advantages generic and generic methods have the characteristics of reusability, type security, and high efficiency. It is usually used in collections and Methods running on collections .. NET 2.0 Class Library provides a new namespace named System. Collections. Generic, which contains several new Generic-based collection classes. You can also create custom generic types and methods. Generic classes and methods receive "type parameters", specifying the type of the object to be operated:

public class Test
 
   {}
 
Type is specified during instantiation.
Test
 
   tree = new Test
  
   (); 
  
 
Using generic types has the following advantages: using generic types can maximize code reuse, protect type security, and improve performance. The most common use of generics is to create a collection class .. The. NET Framework class library contains several new Generic collection classes in the System. Collections. Generic namespace. Use these classes as much as possible to replace common classes, such as the ArrayList in the System. Collections namespace. You can create your own generic interfaces, generic classes, generic methods, generic events, and generic delegation. You can restrict generic classes to access specific data types. Information about types used in generic data types can be obtained through reflection at runtime. The type parameter T is used to define the placeholder for a generic class. It is not a type but only a possible type. During definition, T can be used instead of any type.
When and where to use generics, you need to consider the following events: Do the types you use contain or do not specify data types (such as set types )? If so, creating a generic type will provide more benefits. If your type only operates on a single specified type, you do not need to create a generic class. If you type the operation value type, then the packing and unpacking operations will occur. You should consider using the generic type to prevent the packing and unpacking operations. Generic strong-type checks help you quickly find errors (that is, during compilation rather than runtime) and shorten the bug fixing cycle. Is code expansion encountered when writing multiple class operations and multiple data types (for example, one ArrayList stores only StreamReaders and the other stores StreamWriters )? In fact, it is very easy to write code once and make it work on multiple data types. Generics make the code clearer. By eliminating code bloat and performing force checks, your code becomes easier to read and understand. For the class generic type for different types of arrays, write a "bubble sort" for the array. The idea is for class generics, which are placed beside the class. Because the elements need to be compared in the "bubble sort", the generic type must be constrained to implement the IComparable interface.
namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            SortHelper
 
   isorter = new SortHelper
  
   ();            int[] iarray = { 8, 7, 1, 2, 12 };            isorter.BubbleSort(iarray);            foreach (int item in iarray)            {                Console.Write(item + ",");            }            Console.ReadKey();        }    }    public class SortHelper
   
     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:
About generic constraints where T: IComparable: Limits T to implement the IComparable interface where T: class where T: struct where T: IComparable, new () constrained generics must have constructors. This is boundary thinking about the reason why the bubble algorithm is for (int I = 0; I <= length-2; I ++, for example, there is an array of 5 characters. If the element 0 is finally switched to the fourth digit, it takes four times to call a single digit at a time to reach the fourth digit, that is, for (int I = 0; I <= 5-2, I ++), I goes through four times in sequence: 0, 1, 2, 4. As for fZ? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> keys + keys/wsunvbxbhcmfiber gw907/aoaMKPHByZSBjbGFzcz0 =" brush: java; "> namespace ConsoleApplication1 {class Program {static void Main (string [] args) {Book [] bookArray = new Book [2]; Book book1 = new Book (100, "Book 1"); Book book2 = new Book (80, "Book 2"); bookArray [0] = book1; bookArray [1] = book2; Console. writeLine ("before bubble:"); foreach (Book B in bookArray) {Console. writeLine ("title: {0}, price: {1}", B. title, B. price);} SortHelper Sorter = new SortHelper (); 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 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:
In the above example, the generic type of the method is customized and the generic method is defined.
Namespace ConsoleApplication1 {// method generic public class MethodSortHelper {public void BubbleSort
    
     
(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 1 "); book book2 = new Book (80, "Book 2"); bookArray [0] = book1; bookArray [1] = book2; Console. writeLine ("before bubble:"); foreach (Book B in bookArray) {Console. writeLine ("title: {0}, price: {1}", B. title, B. price);} MethodSortHelper sorter = new MethodSortHelper (); sorter. bubbleSort
    
     
(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 the generic method, except for the following:
MethodSortHelper sorter = new MethodSortHelper();   sorter.BubbleSort
    
     (bookArray); 
    
You can also write as follows:
MethodSortHelper sorter = new MethodSortHelper();   sorter.BubbleSort(bookArray); 
It can be seen that the generic method can implicitly infer whether the wildcard meets the conditions based on the data instance.
Other advantages of the generic model avoid implicit packing and unpacking. The following options include implicit packing and unpacking:
ArrayList list = new ArrayList (); for (int I = 0; I <3; I ++) {list. add (I); // The parameter type received by Add is the reference type object, which contains implicit packing} for (int I = 0; I <3; I ++) {int value = (int) list [I]; // The reference type is strongly converted to the value type. writeLine (value );}
Avoid implicit packing and unboxing with generics:
List
    
      list = new List
     
      ();  for(int i = 0; i < 3; i++)  {    list.Add(i);  }  for(int i = 0; i < 3; i++)  {    int value = list[i];    Console.WriteLine(value);  } 
     
    
The following example shows how to detect errors during compilation without using generics. No errors will be reported during compilation:
List
    
      list = new List
     
      ();  for(int i = 0; i < 3; i++)  {    list.Add(i);  }  for(int i = 0; i < 3; i++)  {    int value = list[i];    Console.WriteLine(value);  } 
     
    
When using generics, you can find errors during compilation:
List
    
      list = new List
     
      ();  int i = 100;  list.Add(i);  string value = (string)list[0]; 
     
    
Use the generic technique to create an alias for the generic type in the current file
using IntList = List
    
     ;  IntList list = new IntList();  list.Add(1); 
    
Use a wildcard alias in different files to define a class derived from a wildcard
public class IntList : List
    
     {}
    

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.