C # Advanced Programming Note Day 5, September 13, 2016 (generics)

Source: Internet
Author: User

"Focus" generics: with generics, you can create classes and methods that are independent of the containing type. We don't have to write many methods and classes of the same functionality for different types, just create a method or class, and here are the features of generics: performance, type safety, binary code reuse, code extensions, naming conventions

1. Performance: Generic and non-generic collection classes System.Collections and System.Collections.Generic in space

Value types are stored on the stack, and reference types are stored on the heap. C # classes are reference types, and structs are value types. NET is easy to convert value types to reference types, so you can use value types anywhere you want objects (objects are reference types). For example, an int can be assigned an object. Converting from a value type to a reference type becomes boxing. If the method requires an object as an argument and passes a value type, the boxing operation occurs automatically. On the other hand, boxed value types can be converted to value types by using a unboxing operation. When unpacking, you need to use the type cast operator.

[Extended] Boxing and unpacking

Under boxing and unpacking, you can handle literals as you would with objects:    string s=10.tostring ();//implicit conversion C # through unpacking (unboxing) and boxing (boxing) you can convert a value type to a reference type and convert the reference type back to a value type.    "Boxing": used to describe converting a value type to a reference type. The runtime creates a temporary reference type "box" for objects on the heap.    int myintnumber=20;    Object Myobject=myintnumber; Displays the transform        "unboxing" used to describe the opposite procedure, where the previously boxed value type is cast back to the value type. The term "cast" is used here because of the display of this conversion.    int myintnumber=20;    Object myobjet=myintnumber;//Boxing myintnumber    int mysecondnumber= (int) myobject;//unboxing cast        ★ Only the previously boxed variables can be disassembled. When MyObject is not a boxed int, an exception is thrown if the last line is executed.    !! Here is a warning that when unpacking, you must be very careful to ensure that the resulting value variable has enough space to store the left and right bytes in the value of the unboxing. For example, C # int has 32 bits, so unpacking a Long value (64 bits) to int causes a InvalidCastException exception.    long mylongnumber=32323131;    Object Myobject=mylongnumber;    int myintnumber= (int) myObject;

Example System.Collection in a ArrayList class in a unboxing ArrayList storage object, the Add () method is defined as requiring an object as an argument.

1 varlist=NewArrayList ();2List.add ( -);//Boxing, converting a value type to a reference type3 intI1= (int) list[0];//Unpacking4 5 foreach(intI2inchlist)6 {7Console.WriteLine (I2);//to disassemble the box8}

>> Boxing and unpacking are easy to use, but the performance penalty is large, especially when traversing many items.

  

The List<t> class in System.Collections.Generic does not use objects, but rather defines the type when used. In the following example, the generic definition of the,list<t> class is int, so the int type is yo ing in the JIT compiler dynamically generated class and no longer unboxing the container

1 varlist=Newarraylist<int>();2List. ADD ( A);//not in boxing3 inti1=list[0];//No more unboxing conversions4 foreach(intI2inchlist)5 {6 Console.WriteLine (i2);7}

2. Type safety

As with the ArrayList class, if you use an object, you can add any type to the collection. The following example adds an integer, a string, and an object of type MyClass to the collection of ArrayList types.

    

1 varlist=NewArrayList ();2 3List. ADD ( A);4List. ADD ("GELLW");5List. ADD (NewMyClass ());6 7 //When using the following foreach to iterate, not all elements can be cast to int and a run exception is thrown8 foreach(intI2inchlist)9 {Ten Console.WriteLine (i2); One}

If the generic type T in the generic class list<t> defines the type that is allowed to be used. With a definition such as list<int>, you can only add an integer type to the collection. The compiler will not compile this code because the ADD parameter is invalid

  

1 var list=new arraylist<int>(); 2 list. ADD (+); 3 list. ADD ("geell"); // compile-time error 4 list. ADD (new MyClass ()); // compile-time error. 

Extension

  

var: the variable needs to infer the type of the variable based on the initialization expression and can only be a local variable. Must be assigned at the same time when declaring.

3. Reuse of binary code

1 varlist1=Newlist<int>();2List1. ADD ( -);3 4 varList2=NewList<stirng>();5List2. ADD ("STRINGHISDM");6 7 varlist3=NewList<myclass>();8List3. ADD (NewMyClass ());

4. Naming conventions

    • The name of a generic type is prefixed with the letter T.
    • If there is no special requirement, the generic type allows the use of any class substitution, and only one generic type can be used with the character T as the name of the generic type.
    • 1  Public class List<t>{}23publicclass linkedlist<t>{}
    • If a generic type has a specific requirement (for example, it must implement an interface or derive from a base class), or if two or more generic types are used, a descriptive name should be used for the generic type:
    • 1  Public Delegate void Eventhandle<teventargs> (object  Sender,teventargs e); 2 3  Public Delegate  from ); 4 5  Public class sortedlist<tkey,tvalue>{}

C # Advanced Programming Note Day 5, September 13, 2016 (generics)

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.