. NET extension Methods (ii)

Source: Internet
Author: User
Tags mscorlib

Previous essay. NET extension Method (i) has a general introduction to the extension method, this is a supplement, let's look at a few details of the extension method:

One, the extension method has the inheritance

When extending a type using an extension method, it also extends the derived class, so the previous question "What happens if you add an extension method to an object?" "Of

The answer is--all types will extend the method. The object class has withstood the test of time, and we seem to find no more suitable reason to extend the object class. From the other

Perspective, if you extend the object class, it is likely to pollute the "smart-sensitive tip" so that it fills up too much junk information (because many types do not use the method at all).

The extension method allows the method to be equivalent to the extended type original method exists (here is a ray)

Because of the difficult comprehension of the Chinese language expression, we can use the code to explain it directly, such as the following code snippet:

    public static class Stringextentsion    {public        static string ToString (this string str)        {            return ' Extentsion "+ str;        }    }    Class program    {        static void Main (string[] args)        {            string str = "Test";            Console.WriteLine (str. ToString ()); The output is: test, it is said that the compiler will prefer the original class instantiation method, if no matching method to find the extension method            Console.read ();        }    }

The code snippet above is known: the extension method in the Stringextentsion class the original ToString method of ToString and the string class, for the client code, their syntax representation is the same,

But essentially one is the static method of the Stringextentsion class, and the other is the instantiation method of the string class. However, the compile run did not produce an error, nor did it produce a warning. So in this case, it's very easy to "bury the Thunder",

Accidentally will be in the strokes. One might say, "I'll take care not to be with." NET class library with the same name as you can. But can you guarantee that the. NET 6, or even the. Net 10 method name is not the same as the one you wrote?

Therefore, there is a versioning problem with the extension method .

 

The extension method allows the same extension method to coexist in two or more classes

    public static class Stringextentsion    {public        static bool IsEmpty (this string str)        {            return string. Isnullorwhitespace (str);        }    }    public static class Otherstringextentsion    {public        static bool IsEmpty (this string str)        {            return String. Isnullorwhitespace (str);        }    }    Class program    {        static void Main (string[] args)        {            string str = null;            BOOL result = str. IsEmpty (); This writing generates a compile warning: ambiguous invocation, because it can find two extension methods            bool result = Stringextentsion.isempty (str);//must be displayed using the class call static method            Console.WriteLine (result);            Console.read ();        }    }

  

Iv. extending other types of methods

Extension methods can extend not only class types, but also interfaces, enumerations, delegates, structs, arrays, and corresponding generic types.

The extension interface is highlighted here , and any type object that implements an interface can invoke an extension method on the interface. For this feature, we can fully implement the common code that implements the interface

put in the extension method to implement code reuse. from the formal point of view, this feature is "Single Inheritance + Interface" and "multi-inheritance" intermediate products, has been "multi-inheritance" of the shadow.

V. Delegation and Extension methods

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; namespace methoddemo{public    static class Stringextentsion    {public        static string showstring (the This string STR)        {            return "showstring:" + str;        }    }    Class program    {        static void Main (string[] args)        {            string str = "Meng";            func<string> fun = str. showstring;            Fun ();            func<string> fun2 = str. ToString;            Fun2 ();            Console.read ();}}}    

  

If you've seen the. NET extension Method (i), maybe you can guess what I'm going to say next. Yes, take a look at the IL code and see what "weird" the compiler is doing behind the scenes.

By the way, the opportunity to say a few IL instructions.

. method private Hidebysig static void Main (string[] args) CIL managed{. entrypoint//code size (0x37). maxstack 2//Initialize 3 local variables. Locals init ([0] String str, [1] class [Mscorlib]system.func ' 1<string> fun, [2  ] class [Mscorlib]system.func ' 1<string> fun2) IL_0000:NOP//reference of the String object "Meng" into the stack Il_0001:ldstr "Meng" The value of the top of the stack is assigned to the NO. 0 local variable (that is, str), the stack top value out of the stack il_0006:stloc.0//The NO. 0 local variable into the stack (that is, str into the stack) il_0007:ldloc.0//Will Methoddemo.stringex The static method of the Tentsion class showstring the pointer into the stack il_0008:ldftn string methoddemo.stringextentsion::showstring (String)//with two values at the top of the stack as a parameter, Call constructor new a func<string> type of delegate il_000e:newobj instance void class [Mscorlib]system.func ' 1<string>::.cto  R (object, native int) il_0013:stloc.1 Il_0014:ldloc.1//Invoke method of the Fun object Il_0015:callvirt instance!0 class [Mscorlib]system.func ' 1<string>::inv Oke () Il_001a:pop IL_001b:ldloc.0 Il_001c:dup//Instantiate the Str object method pointer of the tostring method into the Stack il_001d:ldvirtftn instance string [mscorlib]system.obj                                                                                  Ect::tostring () Il_0023:newobj instance void class [Mscorlib]system.func ' 1<string>::.ctor (object, native int) Il_0028:stloc.2 IL_0029:LDLOC.2 I       L_002a:callvirt instance!0 class [Mscorlib]system.func ' 1<string>::invoke () Il_002f:pop Il_0030:call Int32 [Mscorlib]system.console::read () Il_0035:pop Il_0036:ret}//End of method Program::main

  

The core IL directive has been given a similar comment, according to the IL directive can be obtained: we were again "deceived" by the compiler once, the fun object is saved by the method pointer is the Methoddemo.stringextentsion class

A pointer to a static method showstring. The Fun2 object holds a pointer to the method's pointer to the ToString method of the Str object.

. NET extension Methods (ii)

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.