8. Generic and generic

Source: Internet
Author: User
Tags new set

8. Generic and generic
First of all, it is a hydrology, because the text content is relatively dry, mainly some introductions and concepts. However, understanding generics is helpful. There is not much code to explain.

Introduction :. after net2.0 was released, the C # programming language began to support generics to enhance its features. Based on this, a new set-centered namespace is introduced in the Basic Class Library: System. collections. generic namespace.

The first question: why should generic be introduced. In fact, it is the difference between it and the array. 1. I have mentioned arrays of C # before. The data structure of arrays can provide a set of same type items with a fixed upper limit. But in many cases, we need more flexible data structures, such as containers that can grow and contract. And the container can save objects that meet a certain condition. 2. type security and performance advantages. (Constraints) in this case, we should start from a non-generic set and gradually transition. 1. Non-generic Collections we know that we often use many classes in the System. Collections namespace in mscorlib. dll to organize data. For example, ArrayList, Hashtable, Queue, Stack, and SortedList. Using these classes will cause many problems. 1. low performance. Especially when operating the data structure (value type ). When we store the structure in a classic collection class, CLR must perform a large amount of memory conversion. 2. Some classic collection classes are not of type security, because they are developed to operate the System. Object Class. Therefore, it can contain any type. Note: Any project created using. net2.0 or later should discard the class in System. Collections and use the class in System. Collections. Generic. First, as mentioned earlier in performance,. net supports two data types: Value Type and reference type. Sometimes we need to use a class variable to represent another class variable, So C # provides a simple mechanism for packing. This allows us to save the value type in the reference type variable. Packing: The displayed process of assigning the value type to the System. Object variable. In this process, the CLR will allocate a new object on the stack and copy the value of the value type to that instance. What is returned to us is the reference of the newly assigned object on the stack. Binning: In contrast to packing, it converts the values stored in the object reference back to the corresponding value type on the stack. (It is more like a type conversion operation, but the semantics is quite different, because the unpacking CLR will check whether the value type is equivalent to the packing type, if yes, copy the value type back to the local stack variable .) Therefore, unlike the conversion, the unpacking must return to the appropriate data type. Note: The objects operated by the Console. WriteLine () method are also of the Object type. Therefore, when output, our values are reboxed. The following describes the steps for packing and unpacking: 1. A new object must be allocated to the managed stack. 2. Stack-based data values must be transferred to the newly allocated memory location. 3. During unpacking, the value of the object stored on the heap must be transferred back to the stack. 4. useless objects on the stack (final) will be recycled. It can be seen that when we operate on a large amount of data, the creation will produce a large number of packing and unpacking operations, and the performance is a big problem. Ideally, we should be able to operate station data in containers without any performance problems, and do not need to use try or catch scopes when obtaining data. (This is exactly what generics implement .) Second, type security as mentioned above, in the System. Collections namespace, most classes operate on the Object type, so they can accommodate any type, which leads to type security problems. In most cases, we need a type-Safe Container to operate on a specific data type. To do this, we need to customize the set of types. However, the custom set does not eliminate the binning loss. For example, no matter which type is used to save integers, we can avoid the binning problem caused by non-generic containers. This requires the use of generics, which can eliminate the loss and security problems caused by the above. Compared with non-generic types, generic types have the following advantages: 1. Better performance will not lead to bin removal loss. 2. type security. They only include the specified type. 3. This greatly reduces the need to build a set of custom types because the base class library provides several pre-fabricated containers. Ii. Functions of generic parameters. For example, the formal names of tags in List <T> Angle brackets are type parameters, which can be commonly referred to as placeholders. <T> read as of T. When creating generic objects, implementing generic interfaces, or calling generic members, the value provided for generic parameters is determined by the developer. 1. When we specify a specific type parameter for a generic class or structure, such as the generic set of the Person class, List <Person>. When you create a List <T> variable, the compiler does not create a new implementation for List <T>, but only processes the actually called generic type members. 2. In addition to specifying type members for a generic class, you can also specify type members (methods and attributes) for the generic members .). For example, List <int> intList; and generic interfaces, interface IComparable <T> 3. System. collections. we have learned the object initialization syntax before using the Generic namespace. Now let's take a look at the set initialization syntax: this syntax feature allows you to use a syntax similar to filling in the basic array, to fill in containers such as ArrayList or List <Y>. Note: Only classes that support the Add () method use the set initialization syntax, which is determined by the ICollection <T> or ICollection interface. If a point Collection class is created, it can be represented as follows: List <Point> mypoint = new List <Point> {new point {x = 1, y = 1 }, new point {x = 2, y = 2 },...}; the advantage of this syntax is to reduce keyboard input, but the disadvantage is to affect readability. This namespace contains several generic classes. List <T> is the most widely used type for dynamic adjustment. Stack <T>, Stack, and a collection of first-in-first-out data, including the push and pop methods, respectively. Queue <T>, Queue, a set of first-in-first-out data, including the Dequeue and Enqueue methods, respectively, indicating to remove the object (and return) at the beginning and add an object at the end of the Queue, in addition, the Peek method returns the object at the beginning of the queue, but does not remove it. SortedSet <T>, the items in this class are automatically sorted, and can be automatically sorted after insertion and removal, so this class is very useful. 4. create custom generic methods/generic structures and classes. In the traditional method, two integers are exchanged: Swap (ref int a, ref int B) {int temp; temp = a; a = B; B = temp ;} if we continue to exchange two Person objects, we must write a new version of swap: Swap (ref Person a, ref Person B) {Person temp; temp = a; a = B; B = temp;} If you need to exchange other data, you need to define more methods, which will cause trouble for maintenance. If you want to have a single method, we need to create methods to operate the Object type, but this will cause problems such as packing, unpacking, type security, display conversion, and so on. If you want to create a method overload with different input parameters, you can use the generic type. The method is as follows: Swap <T> (ref T a, ref T B) {T temp; temp = a; a = B; B = temp ;} we can also create a generic class or structure: public class Point <T >{}, where we can be a double-precision point or an int point. 1. default (T) indicates the default value of A type parameter when used together with the generic type. This is very useful, because a generic type does not know the real supplement in advance, so it cannot be safe to assume what the default value is. The default value is as follows: the default value is 0; the default value of the reference type is null; the field of a structure is set to 0 (Value Type) or null (reference type ). 2. Generic base classes. generic classes can be used as the base classes of other classes. They can define many virtual methods and abstract methods. To do this, generic classes must follow the rules: first, if a non-generic type extends a generic class, a type parameter must be specified for the derived class. Public class B: A <string >{}. class A is A custom generic class. Second, if a generic base class defines a generic virtual method or abstract method, the derived type must use the specified type parameter to override the generic method. Finally, if the derived type is also generic, it can (optional) Reuse the type placeholder. Note that the derived class must comply with any constraints in the base class. 5. Constraints of type parameters: As described in this section, any generic type must have at least one type parameter and specify this type parameter when interacting with a generic type or parameter, this allows us to build type-safe code ... Net platform can use the where keyword to obtain more specific type parameter information. The following constraints are described as follows: where T: struct. This type of parameter <T> must contain the System. ValueType value type in its inheritance chain, that is, it must be a structure. Where T: class, opposite to the above, cannot contain value type, must be a reference type. Where T: new (), this type of parameter <T> must contain a default constructor, because it is unable to predict the format of the sub-definition constructor, therefore, it is very useful to create an instance with a type parameter for a generic type. Note: when there are multiple constraints, the constraint must be listed at the end. Where T: NameOfBaseClass. This type parameter <T> must be derived from the class specified by NameOfBaseClass. Where T: NameOfInterface, same as above, must be derived from the specified interface, multiple interfaces must be separated by commas. For example, if you want to specify the generic Intelligent Operation structure, you can: Swap <T> (ref T a, ref T B) where T: struct {....}. If the Swap method is restricted in this way, the Swap method cannot be used to exchange other string objects, for example, because string is of the reference type. 6. Summary This section mainly describes some advantages of the generic container compared to the previous classic container. Type is safe, efficient, and reduces the amount of code. In addition, I also know some knowledge about generic constraints.

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.