30-minute generic tutorial (1)

Source: Internet
Author: User

Let's take a look at the definition of the most common generic type List <T>.

(The real definition is much more complicated than this one. I deleted a lot of things here)

 
 
  1. [Serializable]  
  2. public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>  
  3. {  
  4.     public T this[int index] { get; set; }  
  5.     public void Add(T item);  
  6.     public void Clear();  
  7.     public bool Contains(T item);  
  8.     public int IndexOf(T item);  
  9.     public bool Remove(T item);  
  10.     public void Sort();  
  11.     public T[] ToArray();  

The List is followed by a <T>, indicating that it operates on an unspecified data type T, representing an unspecified data type)

T can be considered as a variable name. T represents a type and can be used anywhere in the source code of List <T>.

T is used as the parameter and return value of the method.

The Add method receives T-type parameters. The ToArray method returns a T-type array.

Note:

Generic parameters must start with T, either T or TKey or TValue;

This is the same as the interface starting with I, which is the Convention.

Let's take a look at a piece of code that uses generic types.

 
 
  1. Var a = new List <int> ();
  2. A. Add (1 );
  3. A. Add (2 );
  4. // This is incorrect. Because you have specified the generic type as int, you cannot add other values in this container.
  5. // This is a compiler error, which improves the efficiency of troubleshooting. If it is a runtime error, I don't know how annoying it is.
  6. A. Add ("3 ");
  7. Var item = a [2];

Note the comments in the above Code

Ii. Effects of generics (1 ):

As a programmer, you do not forget to reuse code when writing code.

Code reuse can be divided into many types. algorithm reuse is a very important one. Suppose you want to write a sorting algorithm for a group of integer data and a sorting algorithm for a group of floating-point data, if there is no generic type, what would you do?

You may have thought of method overloading.

Write two methods with the same name. One method receives the integer array, and the other method receives the floating point array.

But with generics, you don't have to do this. You only need to design a method. You can even use this method to sort a group of string data.

Iii. Functions of generics (2 ):

Assume that you are a method designer. This method requires an input parameter, but you can determine the type of the input parameter. What will you do?

Some people may immediately refute: "This is not the case !"

Then I will tell you that programming is an experience-based job, and your experience is not enough, and you have never encountered any similar issues.

Another part may consider setting the parameter type to Object. This is indeed a feasible solution, but it may cause the following two problems, if I pass an integer to this method with the same data value type), additional packing and unpacking operations will occur, resulting in performance loss.

If the processing logic in your method does not apply to string parameters, and the user uploads another string, the compiler will not report an error and will only report an error at runtime.

(If the Quality Control Department does not measure the BUG During the runtime, I don't know how much damage it will cause)

This is what we often say: the type is insecure.

Iv. Example of generics:

Generic types such as List <T> and Dictionary <TKey, TValue> are frequently used. Below I will introduce several generic types that are rarely used.

ObservableCollection <T>

When this set changes, corresponding events will be notified.

See the following code:

 
 
  1. Static void Main (string [] args)
  2. {
  3. Var a = new ObservableCollection <int> ();
  4. A. CollectionChanged + = a_CollectionChanged;
  5. }
  6.  
  7. Static void a_CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
  8. {
  9. // You can use Action to determine which operation triggers the event.
  10. // E. Action = policycollectionchangedaction. Add
  11.  
  12. // You can obtain the pre-modification and post-modification content based on the following two attributes:
  13. // E. NewItems;
  14. // E. OldItems;
  15. }

To use this set, you must reference the following two namespaces:

 
 
  1. using System.Collections.ObjectModel;  
  2. using System.Collections.Specialized; 

BlockingCollection <int> is a set of thread security.

Let's take a look at the following code.

 
 
  1. Var bcollec = new BlockingCollection <int> (2 );
  2. // Try to add 1-50
  3. Task. Run () =>
  4. {
  5. // Parallel Loop
  6. Parallel. For (1, 51, I =>
  7. {
  8. Bcollec. Add (I );
  9. Console. WriteLine ("add:" + I );
  10. });
  11. });
  12.  
  13. Thread. Sleep (1000 );
  14. Console. WriteLine ("call Take once ");
  15. Bcollec. Take ();
  16.  
  17. // Wait for an infinite amount of time
  18. Thread. Sleep (Timeout. Infinite );

Output result:

 
 
  1. Join: 1
  2. Add: 37
  3. Call Take once
  4. Join: 13

BlockingCollection <int> can also set the CompleteAdding and IsCompleted attributes to reject new elements.

The. NET Class Library also provides many generic types, which are not described here.


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.