MSIL 靜態類在 IL 定義上和非靜態類的差異

本文來聊聊 MSIL 的基礎知識,給一個 C# 的類標記了 static 以後和標記 static 以前,生成這個類的 IL 代碼有什麼不一樣code

如如下的代碼是一個默認的控制檯程序繼承

class Program
    {
        static void Main(string[] args)
        {
        }
    }

此時生成的 IL 代碼,大概以下string

.class private auto ansi beforefieldinit KakawbaijairKacheberelere.Program
        extends [System.Runtime]System.Object

而若是給 Program 加上靜態,如如下代碼,生成的 IL 代碼是和以前不相同的it

static class Program
    {
        static void Main(string[] args)
        {
        }
    }

生成的 IL 代碼以下class

.class private abstract sealed auto ansi beforefieldinit
  KakawbaijairKacheberelere.Program
    extends [System.Runtime]System.Object

複習一下 IL 代碼的知識基礎

在 MSIL 裏,採用 .class 表示這是類型的定義,類型定義的格式大概以下命名空間

.class [訪問權限] [其餘修飾] [命名空間].[類名] extends [繼承的基類]

能夠看到上下兩個 IL 代碼的不一樣在於,若是標記了 static 那 IL 將加上 abstract sealed 修飾。和 C# 代碼的含義相同,經過 abstract 表示此類型不能被實例化,經過 sealed 表示此類型不能被繼承。所以這就構成了靜態類的特色,不能被建立實例,也不能被繼承權限

相關文章
相關標籤/搜索