Principles and Rules that need to be paid attention to about the extension method, and rules for extension

Source: Internet
Author: User
Tags mscorlib

Principles and Rules that need to be paid attention to about the extension method, and rules for extension

 

  • C # Only extension methods are supported. Extension attributes, Extension events, and extension operators are not supported.
  • The extension method must be declared in a non-generic static class, and the extension method must have at least one parameter, and only the first parameter can be marked with the this keyword.
  • C # When finding a method in a static class, the static class must have a file scope, that is, the extension method must be defined in the top-level static class, but not in the nested static class.
  • Since static classes can take any name, the C # compiler takes some time to look for extension methods. It must check all static classes in the file scope, scan all their static methods to find a match;

I can't understand it like this. The performance is only lost during compilation. After compilation, it will be the same as the normal static method call. There is no difference, the reason for this conclusion is that the following two call methods and the corresponding IL code are compared:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Extention{    class Program    {        static void Main(string[] args)        {            var dt = DateTime.Now;            var dtString = dt.DT();            var dtString1 = Extention.Extention1.DT(dt);            var dtString2 = Extention.Extention1.DT1(dt);            Console.ReadLine();        }    }    public static class Extention1    {        public static string DT(this DateTime dt)        {            return dt.ToString();        }        public static string DT1(DateTime dt)        {            return dt.ToString();        }    }}

The IL code generated by the three calls to DT in the Main function is as follows:

 

C # How does the compiler quickly locate the matching of extension methods?

In C #, once the first parameter of a static method is marked with this keyword, the compiler will apply a custom ExtensionAttribute to the method internally;

In addition, as long as any static class contains at least one extension method, its metadata will also apply this feature. Similarly, if a set of programs contains at least one static class that meets the preceding features, this feature is also applied to its metadata,

In this way, if the Code calls a non-existent instance method, the compiler can quickly scan all referenced assembly, determine which of them contain the extension method, and then in these assembly, you can only scan static classes that contain extension methods,

In each such static class, you can only scan extension methods to find matching. With these technologies, the code can be compiled as quickly as possible;

.class public auto ansi abstract sealed beforefieldinit Extention.Extention1extends [mscorlib]System.Object{.custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = (01 00 00 00)// Methods.method public hidebysig static string DT (valuetype [mscorlib]System.DateTime dt) cil managed {.custom instance void [mscorlib]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = (01 00 00 00)// Method begins at RVA 0x2088// Code size 19 (0x13).maxstack 1.locals init ([0] string CS$1$0000)IL_0000: nopIL_0001: ldarga.s dtIL_0003: constrained. [mscorlib]System.DateTimeIL_0009: callvirt instance string [mscorlib]System.Object::ToString()IL_000e: stloc.0IL_000f: br.s IL_0011IL_0011: ldloc.0IL_0012: ret} // end of method Extention1::DT.method public hidebysig static string DT1 (valuetype [mscorlib]System.DateTime dt) cil managed {// Method begins at RVA 0x20a8// Code size 19 (0x13).maxstack 1.locals init ([0] string CS$1$0000)IL_0000: nopIL_0001: ldarga.s dtIL_0003: constrained. [mscorlib]System.DateTimeIL_0009: callvirt instance string [mscorlib]System.Object::ToString()IL_000e: stloc.0IL_000f: br.s IL_0011IL_0011: ldloc.0IL_0012: ret} // end of method Extention1::DT1} // end of class Extention.Extention1
  • Multiple Static classes can define the same extension method. If the compiler detects that two or more extension methods exist, it will prompt that the call is ambiguous, in this case, you need to call the static method syntax instead of the instance method syntax.
  • When you use an extension method to extend a type, the derived class is also extended. Therefore, do not use the Object as the first parameter of the extension method. Otherwise, this method can be called in all expressions.
  • There is a version control problem with the extension method (two identical extension methods are defined for the same type, and later users will overwrite the previous ones, resulting in inconsistent behavior)

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.