Extension methods can "add" methods to existing types without having to create new derived types, recompile, or otherwise modify the original type. The extension method must be a static method and can be invoked just like an instance method. A method that is actually defined in the same name has a higher precedence than the extension method.
Let's take a look at the example of how to use the extension method in the list type frequently, first look at how list is defined:
Summary:Represents a strongly typed list of objects that can is accessed by index.Provides methods to search, sort, and manipulate lists. To browse the. NETThe Framework source code for this type, see the Reference source.//Type parameter:T:The type of elements in the list. [Serializable] [DebuggerDisplay ("Count = {count}")] [DebuggerTypeProxy (typeof (Mscorlib_collectiondebugview<>))]PublicClasslist<T>:ilist<T>,icollection<T>,IList,ICollection,ireadonlylist<T>,ireadonlycollection<T>,ienumerable<T>,IEnumerable {Summary:Initializes a new instance of the System.collections.generic.list<t> classThat's empty and has the default initial capacity. [Targetedpatchingoptout ("Performance critical to inline across NGen image boundaries")]PublicList ();////Summary: //Initializes a new instance of the System.collections.generic.list<t> class //that contains elements copied from the Specified collection and have sufficient //capacity to accommodate the number of elements Copie D. ////parameters: //collection: //the collection whose elements is copied to the new list. ////exception: // System.ArgumentNullException: //collection is null. public List ( ienumerable<t> collection); ...}
We do not see a definition of the Union method in the type definition of the list, but when we invoke it, it appears:
<span style="White-space:pre" ></span>///<summary>Use by collection///</summary>///<param name= "Needsearchlist" ></param>///<param name= "Areaid" ></param>///<returns></returns>Public list<arealineinfomodel>Usesetsearchcollection (List<arealineinfomodel> Needsearchlist,int Areaid) {if (needsearchlist = =null | | !needsearchlist.any ())ReturnNullConstint AREA15 =15;var area15list =New List<arealineinfomodel> ();Constint area16 =16;var area16list =New List<arealineinfomodel> ();Constint area17 =17;var area17list = new list<arealineinfomodel> (); Needsearchlist.foreach (M + = {if (M.areaidlist.contains (AREA15)) Area15list.add (m); Span class= "Hljs-keyword" >if (M.areaidlist.contains (AREA16)) Area16list.add (m); if (M.areaidlist.contains (AREA17)) Area17list.add (m);}); if (Areaid = area15) return area15list.union (area16List). Union (area17list). ToList (); if (Areaid = area16) return area16list.union (area15List). Union (area17list). ToList (); if (Areaid = area17) return area17list.union (area15List). Union (area16list). ToList (); return null;}
Where does the union approach come from? Let's go to the definition and take a look at:
Namespacesystem.linq{public static class enumerable {... public static ienumerable<tsource> Union<TSource > (this ienumerable<tsource> First, ienumerable<tsource> second) {if (first = = null) throw Error.argumentnull ( "first"); if (second = null) throw Error.argumentnull ( "second"); return unioniterator<tsource> (first, second, null);}}
So, in other words, an instance of list can call the Union method inside the enumerable, if we do not know the extension method this matter, with the usual idea, through the inheritance relationship to find the Union method, we will find that the list does not implement the Union method, Also, the Union method is not defined in the inherited interface. This is more puzzling, this is not against the object-oriented three basic principles? After that, let's start by implementing an extension method:
PublicInterfaceifreshlist<t> {}PublicStaticClassTestjinni {PublicStatic Ifreshlist<tsource> union<tsource> (This ifreshlist<tsource> first, ifreshlist<tsource> second) {return second;} } public class mylist<t>: ifreshlist<t> {} Public class use { publi c void meth () { var temilist=new mylist<int> (); var mdaidnnf = new mylist<int> (); temilist.union (MDAIDNNF);}}
This is just a simple example, you can do your own extension method.
Extensions are available to all objects:
public static Class Extendext
{
public static void Funcext (thisobject obj)
{
int b = 0;
}
}
MSDN defines extension methods as follows: "extension methods are defined as static methods, but they are invoked through the instance method syntax. Their first argument specifies which of the methods the method acts on
Type, and the parameter is prefixed with the This modifier. In layman's words, the extension method is independent of the name of the static class, and only needs to define a static method inside a static class, the first parameter must start with this T,
This t is a generic type.
Summary:
Essentially: The extension method is to destroy the original hierarchy, and accelerate the business logic processing through the network structure;
Extension methods do not change the code of the extended class, without recompiling, modifying, deriving the extended class;
Extension methods cannot access private members of the extended class;
Extension methods are overwritten by the method with the same name as the extended class, so we need to assume the risk of being covered at any time by implementing the extension method;
The extension method seems to implement the object-oriented extension to the modification of the feature, but also against the object-oriented inheritance principle, the derived class of the extended class can not inherit the extended extension method, and thus violate the object-oriented polymorphism. ;
In our stable reference to the same version of the class library, but we do not have the source code of the class library, we can use the extension method, but from the extensible, maintainable and versioning aspects of the project, it is not recommended to use extension methods to extend the class.
Article reproduced from: 52469476
(go) C # extension method