Analysis of generic methods based on C # programming (i)

Source: Internet
Author: User
C#2.0 introduced the generic feature, due to the introduction of generics, to a certain extent, greatly enhance the vitality of C #, you can complete the c#1.0 need to write complex code to complete some of the functions. But as a developer, it is love and hate for generics, Love is its powerful function, and the efficiency of this feature increases, hate is the generics in the complex time, will present quite complex grammatical structure.


This complexity is not only for beginners, but for some of the development experience. NET developers, is also a less easily mastered feature.


Next, let's look at the features c#2.0 added: generics.


I. Overview of the basic features of generics


In actual project development, any API that uses object as a parameter type and return type may at some point involve strongly typed conversions. Referring to the strong type conversion, estimated that many developers first reaction is "efficiency" this time, for strong types of pros and cons of the main look at the user's environment, there is no absolute bad things, there is no absolute good, the issue of strong type is not the focus of this time, do not focus on the introduction.


Generics are a special mechanism provided by the CLR and C # to support another form of code reuse, called "algorithm reuse." Generics implement the parameterization of types and methods, and generic types and methods can also let parameters tell the consumer what type to use.


The benefits of generics: better compile-time checking, more information that can be directly represented in code, more IDE support, better performance. One might wonder why generics bring so many benefits, using a generic API that does not differentiate between different types, which is equivalent to accessing that API in a dynamic environment.

The CLR allows the creation of generic references and generic value types, but does not allow the creation of generic enumerations, and the CLR allows the creation of generic interfaces and generic delegates, which the CLR allows to define generic methods in reference types, value types, or interfaces. When you define a generic type or method, any variables (such as: T) that are specified for the type are referred to as type parameters. (t is a variable name that can be used anywhere in the source code to use a data type, T) in C # The generic parameter variable either becomes t, or at least one capital T begins.

Two. Overview of generic classes, generic interfaces, and generic delegates

1. Generic class

A generic type is still a type, so you can derive from any type. When a generic type is used and a type argument is specified, a new type object is actually defined in the CLR, and the new type object is derived from the type derived from the generic type.

One way to use generic type parameters at the time of the JIT compilation of the generics, the CLR obtains the IL, replaces it with the specified type arguments, and then creates the appropriate native code.

If a type argument is not supplied for a generic type parameter, then it is an unbound generic type. If a type argument is specified, the type is the constructed type.

A constructed type can be either developed or closed, the development type also contains a class Ixngcanshu, and the enclosing type is not developed, and each part of the type is unambiguous. All code is actually executed in the context of a closed constructed type.

Generic classes are in the. NET is used primarily in collection classes, most of which are in System.Collections.Generic and System.Collections.ObjectModel classes. The following is a simple introduction to a generic collection class:

(1). Synchronizedcollection: Provides a thread-safe collection that contains an object of the type specified by the generic parameter as an element.

[ComVisible (False)]public class synchronizedcollection<t>: Ilist<t>, Icollection<t>, IEnumerable <t&gt, IList, ICollection, IEnumerable {//<summary>//Initialize <see cref= "T:system.collections.generic .    Synchronizedcollection ' 1 ' A new instance of the/> class.    </summary> public synchronizedcollection (); <summary>////Initialize <see cref= "by using objects that are used to synchronize access to thread-safe collections T:system.collections.generic.synchronizedcollection    A new instance of the ' 1 '/> class. </summary>//<param name= "SyncRoot" > objects that are used to synchronize access to thread-safe collections. </param><exception cref= "T:System.ArgumentNullException" > <paramref name= "syncRoot"/> is null.    </exception> public Synchronizedcollection (object syncRoot); <summary>//////Initialize <see cref= "T: Using the specified list of enumerable elements and the objects used to synchronize access to the thread-safe collection.    System.Collections.Generic.SynchronizedCollection ' 1 ' A new instance of the/> class. </summary>//<param name= "SyncRoot" > objects that are used to synchronize access to thread-safe collections. </param> <param name= "LIst "> <see cref=" T:System.Collections.Generic.IEnumerable ' 1 "/> Collection of elements used to initialize thread-safe collections. </param> <exception cref= "T:System.ArgumentNullException" ><paramref name= "SyncRoot"/> or < Paramref name= "list"/> is null.    </exception> public Synchronizedcollection (Object syncRoot, ienumerable<t> list); <summary>//////Initialize <see cref= "T: Using the specified array of elements and the object used to synchronize access to the thread-safe collection.    System.Collections.Generic.SynchronizedCollection ' 1 ' A new instance of the/> class. </summary>//<param name= "SyncRoot" > objects that are used to synchronize access to thread-safe collections. </param> <param name= "list" >/> <see "cref=" T:System.Array for initializing thread-safe collection <paramref name= "T"/& type element gt;. </param> <exception cref= "T:System.ArgumentNullException" ><paramref name= "SyncRoot"/> or < Paramref name= "list"/> is null.    </exception> public Synchronizedcollection (object syncRoot, params t[] list);    <summary>///Add items to the thread-safe read-only collection. </summary>//<paraM name= "Item" > the element to add to the collection. </param> <exception cref= "T:System.ArgumentException" > set the value to NULL, or not the correct generic type for the collection <paramref name= "T"/ >.    </exception> public void Add (T item);    <summary>///Removes all items from the collection.    </summary> public void Clear ();    <summary>////starts from a specific index and copies the elements in the collection to the specified array. </summary>//<param name= "Array" > <paramref copied from the collection name= "T"/> The target of the type element <see cref= "t:system.ar Ray "/>. </param> <param name= "index" > The zero-based index in the array where copying started.    </param> public void CopyTo (t[] array, int index);    <summary>///Determines whether the collection contains elements with a specific value.    </summary>//////<returns>///TRUE if element value is found in the collection; False otherwise. </returns>//<param name= "Item" > The object to locate in the collection. </param> <exception cref= "T:System.ArgumentException" > set the value to NULL, or not the correct generic type for the collection <paramref name= "T"/ >.    </exception> public bool Contains (T item); <summary&gT    Returns an enumerator that iterates through the synchronization collection. </summary>/////<returns> a <see cref= "T:System.Collections.Generic.IEnumerator ' 1"/&G    t; The object that is used to access the type stored in the collection.    </returns> public ienumerator<t> GetEnumerator ();    <summary>///Returns the index of the first occurrence of a value in the collection.    </summary>//////<returns> The zero-based index of the first occurrence of the value in the collection. </returns>//<param name= "Item" > removes all items from the collection. </param><exception cref= "T:System.ArgumentException" > set the value to NULL, or not the correct generic type for the collection <paramref name= "T"/ >.    </exception> public int IndexOf (T item);    <summary>///Inserts an item into the collection at the specified index. </summary>//<param name= "index" > The zero-based index of the element to retrieve from the collection. </param><param name= "Item" > the object to insert into the collection as an element. </param> <exception cref= "T:System.ArgumentOutOfRangeException" > Specified <paramref name= "index"/> Less than 0 or greater than the number of items in the collection. </exception> <exception cref= "T:System.ArgumentException" > Set the value toNULL, or not the correct generic type of the collection <paramref name= "T"/>.    </exception> public void Insert (int index, T item);    <summary>////Removes the first occurrence of a specified item from the collection.    </summary>//////<returns> True if the item was successfully removed from the collection, or false otherwise. </returns>//<param name= "Item" > The object to remove from the collection.    </param> public bool Remove (T item);    <summary>///Remove the item at the specified index from the collection. </summary>//<param name= "index" > The zero-based index of the element to retrieve from the collection. </param> <exception cref= "T:System.ArgumentOutOfRangeException" > Specified <paramref name= "index"/> Less than 0 or greater than the number of items in the collection.    </exception> public void RemoveAt (int index);    <summary>///Removes all items from the collection.    </summary> protected virtual void clearitems ();    <summary>///Inserts an item into the collection at the specified index. </summary>//<param name= The zero-based index in the "Index" > collection, where the object is inserted. </param><param name= "Item" > the object to insert into the collection. </param> <exception cref= "T:system.argumentoutOfrangeexception "> Specified <paramref name=" index "/> less than 0 or greater than the number of items in the collection. </exception> <exception cref= "T:System.ArgumentException" > set the value to NULL, or not the correct generic type for the collection <paramref name= "T "/>.    </exception> protected virtual void InsertItem (int index, T item);    <summary>///Removes the item from the collection specified <paramref name= "index"/>. </summary>//<param name= "index" > The zero-based index of the element to retrieve from the collection. </param> <exception cref= "T:System.ArgumentOutOfRangeException" > Specified <paramref name= "index"/> Less than 0 or greater than the number of items in the collection.    </exception> protected virtual void RemoveItem (int index);    <summary>////Use another item to replace the item at the specified index. </summary>//<param name= "index" > The zero-based index of the object to replace. </param><param name= "Item" > the object to replace. </param> <exception cref= "T:System.ArgumentOutOfRangeException" > Specified <paramref name= "index"/> Less than 0 or greater than the number of items in the collection.    </exception> protected virtual void SetItem (int index, T item); <summary&gT    Returns an enumerator that iterates through the synchronization collection. </summary>/////<returns> a <see cref= "T:System.Collections.Generic.IEnumerator ' 1"/&G    t; The object that is used to access the type stored in the collection.    </returns> IEnumerator ienumerable.getenumerator ();    <summary>////starts from a specific index and copies the elements in the collection to the specified array. </summary>//<param name= "Array" > <paramref copied from the collection name= "T"/> The target of the type element <see cref= "t:system.ar Ray "/>. </param> <param name= "index" > The zero-based index in the array where copying started.    </param> void ICollection.CopyTo (array array, int index);    <summary>///Add an element to the collection.    </summary>/////<returns> insert position of new element. </returns>//<param name= "Value" > The object to add to the collection.    </param> int Ilist.add (object value);    <summary>///Determines whether the collection contains elements with a specific value.    </summary>///<returns> if element <paramref name= "value" is found in the collection/> true; otherwise false. </returns>//<param name= "Value > The object to locate in the collection. </param><exception cref= "T:System.ArgumentException" ><paramref name= "value"/> is not an object of the type contained in the collection.    </exception> bool Ilist.contains (object value);    <summary>///determines the zero-based index of an element in the collection.    </summary>//////<returns>//<paramref name= "value"/> If found in the collection; otherwise-1. </returns>//<param name= "value" > the element in the collection whose index you want to determine.    </param> int Ilist.indexof (object value);    <summary>///Inserts an object into the collection at the specified index. </summary>//<param name= "index" > The zero-based index at which <paramref name= "value"/> will be inserted. </param><param name= "Value" > the object to insert in the collection. </param> <exception cref= "T:System.ArgumentOutOfRangeException" > Specified <paramref name= "index"/> Less than 0 or greater than the number of items in the collection. </exception> <exception cref= "T:System.ArgumentException" > Set <paramref name= "value"/> to null, Or not the correct generic type for the collection <paramref name= "T"/>. </exception> void Ilist.insert (int index, object value);    <summary>////Removes the first occurrence of a specified object as an element from the collection. </summary>//<param name= "Value" > The object to remove from the collection.  </param> void Ilist.remove (object value); }

(2). Keyedbytypecollection: Provides a collection of items that are used as the type of the key.

[__dynamicallyinvokable] public class keyedbytypecollection<titem>: Keyedcollection<type, TItem> {////    Lt;summary>///Initializes a new instance of the/> class for <see cref= "T:system.collections.generic.keyedbytypecollection ' 1".    </summary> public keyedbytypecollection ();    <summary>/////Initializes a new instance of the <see cref= "t:system.collections.generic.keyedbytypecollection ' 1"/> class based on the specified object enumeration. </summary>//<param name= "items" > generic type <see cref= T:System.Object/> <see "cref=". Collections.Generic.IEnumerable ' 1 "/&GT;, used to initialize the collection. </param> <exception cref= "T:System.ArgumentNullException" ><paramref name= "items"/> is null.    </exception> public keyedbytypecollection (ienumerable<titem> items);    <summary>///Returns the first item in the collection that has a specified type. </summary>///////<returns>//If the reference type is a return type <paramref name= "T"/>, and if it is a value type, the return type <p     Aramref the value of name= "T"/>. If the collection does not contain a type &LT;PARAMREF Name= The object of "T"/>, the default value of the type is returned: If it is a reference type, the default value is NULL, and if it is a value type, the default value is 0. </returns>//<typeparam name= "T" > The type of item to find in the collection. </typeparam> [Targetedpatchingoptout ("Performance critical to-inline this type of method across NGen image Bounda    Ries ")] public T find<t> ();    <summary>///Remove an object with the specified type from the collection.    </summary>//////<returns> objects removed from the collection. </returns>//<typeparam name= "T" > The type of item to remove from the collection. </typeparam> [Targetedpatchingoptout ("Performance critical to-inline this type of method across NGen image Bounda    Ries ")] public T remove<t> (); <summary>///return <see cref= "t:system.collections.generic.keyedbytypecollection ' 1"/> contains the types <    Paramref a collection of objects name= "T"/>. </summary>//////<returns> a type <paramref name= "T"/> <see cref= "T:system.collec tions.   Objectmodel.collection ' 1 "/&gt, containing the object from the original collection's type <paramref name=" T "/>. </returns>//<typeparam name= "T" > The type of item to find in the collection. </typeparam> [Targetedpatchingoptout ("Performance critical to-inline this type of method across NGen image Bounda    Ries ")] public collection<t> findall<t> ();    <summary>///Remove all elements with the specified type from the collection. </summary>/////<returns>/<see cref= "T:System.Collections.ObjectModel.Collection ' 1"/&G    t;, contains the object from the original collection of type <paramref name= "T"/>. </returns>//<typeparam name= "T" > The type of item to remove from the collection. </typeparam> [Targetedpatchingoptout ("Performance critical to-inline this type of method across NGen image Bounda    Ries ")] public collection<t> removeall<t> ();    <summary>///Gets the type of an item contained in the collection.    </summary>//////<returns> <paramref name= "item" type/> specified in the collection. </returns>//<param name= "Item" > the item in the collection whose type you want to retrieve. </param><exception cref= "t:system.argumentnullexceptIon "><paramref name=" item "/> is null.    </exception> [__dynamicallyinvokable] protected override Type GetKeyForItem (TItem item);    <summary>///Insert an element at a specific location in the collection. </summary>//<param name= "index" > The zero-based index at which the <paramref name= "item"/> should be inserted. </param><param name= "Item" > the object to insert in the collection. </param> <exception cref= "T:System.ArgumentNullException" ><paramref name= "item"/> is null.    </exception> [__dynamicallyinvokable] protected override void InsertItem (int index, TItem item);    <summary>////Replace the item at the specified index with a new object. </summary>//<param name= "index" > The zero-based index of the <paramref name= "item"/> to replace. </param><param name= "Item" > The object to add to the collection. </param> <exception cref= "T:System.ArgumentNullException" ><paramref name= "item"/> is null.  </exception> [__dynamicallyinvokable] protected override void SetItem (int index, TItem item); }

The CLR supports generic delegates to ensure that any type of object can be passed to a callback method in a type-safe manner. Generic delegates allow a child type instance to not perform any boxing processing when passed to a callback method. The delegate timing provides only 4 methods: a constructor, a Invlke method, a BeginInvoke method, and a EndInvoke method. If a defined delegate type specifies a type parameter, the compiler defines the method of the delegate class, replacing the parameter type and value type of the method with the specified type parameter.

The above is the C # programming basis of the generic method of parsing (above) the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.