我可不可以這樣理解,性能只是在編譯時(shí)有損失,編譯之后就和普通的靜態(tài)方法調(diào)用一樣了,沒有任何區(qū)別,之所以能得出這個(gè)結(jié)論是因?yàn)橥ㄟ^比較如下的兩種調(diào)用方式和對(duì)應(yīng)的IL代碼:
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();        }    }}Main函數(shù)中對(duì)DT的三種調(diào)用生成的IL代碼如下:
 
C#編譯器是如何快速的定位擴(kuò)展方法的匹配的呢?
在C#中,一旦用this關(guān)鍵詞標(biāo)記了某個(gè)靜態(tài)方法的第一個(gè)參數(shù),編譯器就會(huì)在內(nèi)部向該方法應(yīng)用一個(gè)定制特性ExtensionAttribute;
另外,任何靜態(tài)類只要包含至少一個(gè)擴(kuò)展方法,它的元數(shù)據(jù)也會(huì)應(yīng)用這個(gè)特性,類似的,程序集中只要包含了至少一個(gè)符合上述特點(diǎn)的靜態(tài)類,它的元數(shù)據(jù)中也會(huì)應(yīng)用這個(gè)特性,
這樣一來,如果代碼調(diào)用了一個(gè)不存在的實(shí)例方法,編譯器就能快速的掃描引用的所有程序集,判斷他們哪些包含了擴(kuò)展方法,然后在這些程序集中,可以只掃描包含了擴(kuò)展方法的靜態(tài)類,
在每個(gè)這樣的靜態(tài)類中,可以只掃描擴(kuò)展方法來查找匹配,利用這些技術(shù),代碼能以最快的速度編譯完畢;
.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
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注