Set and generic

Source: Internet
Author: User

Hi, you guys.

Today, we continue to learn <knocking at the door of C #>. Today, we are studying collections and generics. Collection and generics are common knowledge in project development. Learning generics and collections is of great help to our development work.

Set

 

Similar things need to be classified into one category. We often combine correlated objects into a set, and natural numbers into a natural number set. The classmates form a class, the poems made by the poet, and the poems. An object in a set is called an element ). C # provides us with a set of powerful collection classes that implement a variety of different types of sets. we can select the appropriate collection type based on actual use. The following table lists some of the collection classes provided by the FCL (Framework Common Library) class libraries.

Except for the array in the system namespace, all other classes are located in the system. Collections namespace. These classes directly or indirectly inherit some interfaces to implement their own powerful functions. We used a foreach loop statement in the project to traverse a set or dataset. So how does foreach implement traversal of a set or dataset? (Instead of traversal, it is an iteration. For the concept of iteration, you can refer to Recursive Algorithms in some data structure books ). All the collection classes provided by FCL directly or indirectly implement the ienumerable interface, which declares a method named getienumerator. This method returns a class that inherits the ienumerator interface. We usually call this class an iterator.

// Ienumerable interface public interface ienumerable {ienumerator getienumerator ();}

Ienumerable Interface Class

// Ienumerator interface public interface ienumerator {bool movenext (); // obtain the next Element Object current {Get;} // obtain the current element void reset (); // set the enumeration number to its initial position}

Ienumerator Interface Class

The foreach statement is used to access the iterator to obtain the elements in the set. The icollection interface is also a basic interface that inherits the ienumerable interface and adds a copy () method, a Count attribute, and two attributes for synchronization.

// Icollection interface public interface icollection: ienumerable {void copy (system. array array, int index); // copy to the array int count {Get;} // number of elements bool issynchronized; // whether to synchronize object syncroot {Get ;} // synchronization object}

The ilist interface and idictionary interface all inherit from the icollection interface.

For some methods of various collection classes, you can continue to practice it yourself. This chapter mainly describes generic classes. In fact, more people will use generics in projects, because collections have a drawback.

 

Disadvantages of collection classes

 

Let's take a look at the following code:

Arraylist list = new arraylist (); lsit. Add (10); // Add the element int n = (INT) lsit [0]; // retrieve the element

 

Because all types inherit the object type, when we call the. Add () method to add elements to the set, the system will default to the object type. In this case, if the added element is not a reference type but a value type, the value type is converted to a reference type when an element is added to the set. Similarly, when we read an element, we need to unpack it to convert the object type to the value type. In doing so, there are three disadvantages:

First, some performance loss may occur during packing and unpacking.

2. What types of data are put into the set, which is not conducive to the strict type security check by the compiler.

Third, display the conversion type, reducing the readability of the program. Note (now the computer is getting faster and faster, and performance is not the only goal. The cost of software development lies in software maintenance and upgrade. Therefore, improving code readability can reduce software development costs .)

 

ArrayList   list=new ArrayList();list.Add(10);list.Add("hello");foreach(int element in list){   int n=(int)element;}

The above Code does not cause compilation errors. The Operation will appear, because "hello" cannot be converted to the int type. Now we can see the disadvantages of the Collection class, so what is better for the generic class than the set? In fact, it is not hard to imagine that a wildcard is better than a set, and it must be a weak set. Where the collection is weak, there is no restriction on the element type of the Collection class.

 

Generic

 

The generic type is basically the same as the set function. The only difference is that the element type of the generic type is controlled by us. It is the type we specify, not the object type of the ancestor of everything. The generic type has a parameter list <t>. t represents the element type in the entire class. The T type is uncertain and abstract. When we instantiate a class, the elements of the abstract type are embodied, and the parameters of the specific type will replace T. Program Viewing:

// Generic class public class generic <t> {public void check () {console. writeline (this. getType (); // type of the output t} // instantiate the generic class generic <int> instanceint = new generic <int> (); instanceint. check (); // The output type is system. int32generic <string> instancestring = new generic <string> (); instancestring. check (); // The output type is system. string;

T in a generic class is an abstract type. It will be embodied only when it is instantiated. For example, the above instanceint is to embody T in the generic class into the int type. Instancestring: The T type of the generic class is embodied in the string type. We can define the generic class and agree or define the generic method and interface. See the following code:

 

// Generic public static void swap <t> (ref t a, ref t B) {T = A; A = B; B = T ;}

At this time, both A and B are abstract and unknown types.

Static void Main(string[] args){   int x=100;   int y=200;  Swap<int> (ref x,ref y);Console.WriteLine("x={0},y={1}",x,y);}

When we call a generic method, the parameters are embodied.

C # provides us with some generic classes:

List <t>
Stack <t>
Queue <t>
Sortedlist <tkey, tvalue>
Dictionary <tkey, tvalue>

For some of their methods, you can refer to the relevant manual. It is very important to learn programming by viewing the manual. Well, today's generics and collections are here. Finally, I would like to share with you one sentence from the author. "Honed programming skills in practice, and thought about the essence of programming ".

Set and generic

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.