Refresher of IL explains “this pointer” in C#

來源:互聯網
上載者:User

這篇文章裡,用il語言解釋一下static方法和non-static方法在調用的時候,堆棧頂部傳遞參數的不同形式。
首先看一段代碼:
 class TestClass
    {
        public static readonly int i = 10;
        static void Main(string[] args)
        {           
            TestClass testClass = new TestClass();
            TestStatic();
            testClass.NonStatic();
        }

        public static void TestStatic()
        {
        }

        public void NonStatic()
        {
        }
    }

反編譯以後得到:
.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       21 (0x15)
  .maxstack  1
  .locals init ([0] class TestConcoleApp.TestClass testClass)
  IL_0000:  nop
  IL_0001:  newobj     instance void TestConcoleApp.TestClass::.ctor()
  IL_0006:  stloc.0
  IL_0007:  call       void TestConcoleApp.TestClass::TestStatic()
  IL_000c:  nop
  IL_000d:  ldloc.0
  IL_000e:  callvirt   instance void TestConcoleApp.TestClass::NonStatic()
  IL_0013:  nop
  IL_0014:  ret
} // end of method TestClass::Main

首先,關於this pointer,可以參考ibm的文檔:
http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr035.htm

注意藍色的這一行。這一行說明了一個問題,在使用static方法和non-static方法的時候,static方法並不pass this pointer到stack中去。而non-static方法確需要傳遞一個instance的reference到stack中去。

因為,在
  IL_0001:  newobj     instance void TestConcoleApp.TestClass::.ctor()
  IL_0006:  stloc.0
指令中,儲存了新執行個體化的一個變數到loc.0中去了,然後在調用static方法的時候,堆棧的頂部是沒有obj的reference的。而調用non-static方法的時候,需要傳遞一個obj的reference到堆棧的頂部去。

如果大家想繼續深入瞭解為什麼static方法不需要傳遞一個obj的reference,可以參考compile time 和 run time的區別,下面是一篇ibm的文檔:
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/proguide/ref/cvfltar.htm

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.