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)
- [Serializable]
- public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>
- {
- public T this[int index] { get; set; }
- public void Add(T item);
- public void Clear();
- public bool Contains(T item);
- public int IndexOf(T item);
- public bool Remove(T item);
- public void Sort();
- 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.
- Var a = new List <int> ();
- A. Add (1 );
- A. Add (2 );
- // This is incorrect. Because you have specified the generic type as int, you cannot add other values in this container.
- // 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.
- A. Add ("3 ");
- 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:
- Static void Main (string [] args)
- {
- Var a = new ObservableCollection <int> ();
- A. CollectionChanged + = a_CollectionChanged;
- }
-
- Static void a_CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
- {
- // You can use Action to determine which operation triggers the event.
- // E. Action = policycollectionchangedaction. Add
-
- // You can obtain the pre-modification and post-modification content based on the following two attributes:
- // E. NewItems;
- // E. OldItems;
- }
To use this set, you must reference the following two namespaces:
- using System.Collections.ObjectModel;
- using System.Collections.Specialized;
BlockingCollection <int> is a set of thread security.
Let's take a look at the following code.
- Var bcollec = new BlockingCollection <int> (2 );
- // Try to add 1-50
- Task. Run () =>
- {
- // Parallel Loop
- Parallel. For (1, 51, I =>
- {
- Bcollec. Add (I );
- Console. WriteLine ("add:" + I );
- });
- });
-
- Thread. Sleep (1000 );
- Console. WriteLine ("call Take once ");
- Bcollec. Take ();
-
- // Wait for an infinite amount of time
- Thread. Sleep (Timeout. Infinite );
Output result:
- Join: 1
- Add: 37
- Call Take once
- 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.