C# enum類型的版本問題

在一個Main函數裏調用另外一個dll,記爲 TestLibrary.dll裏的一個常量值。代碼如下:

Main函數:
using lib;
internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine(ConstTest.A);
            Console.WriteLine(ConstTest.B);
            Console.WriteLine(ConstTest.C);
        }
    }

Lib.dll裏的代碼:
namespace Lib
{
    public enum ConstTest
    {
        A,
        B,
        C
    }
}

將上面的代碼進行編譯,設Main函數存在的exe爲Study.exe。
測試一:在命令行中執行exe,結果爲:
A
B
C

現在將 TestLibrary.dll 裏的代碼更改爲:
namespace Lib
{
    public enum ConstTest
    {
        B,
        C
    }
}
重新編譯  TestLibrary.dll  ,不要重新編譯Main函數,並將新的Lib.dll覆蓋原來的 TestLibrary.dll 。再次執行Study.exe,結果爲:
測試二:
B
C
2

如果在執行Study.exe時,不引用Lib.dll,將結果將會報錯:
測試三:

說明無法加載到所需要的Lib.dll程序集;

原因:
利用il dasm.exe打開Study.exe,查看裏面的Main函數的IL代碼,如下:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       38 (0x26)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  box        [TestLibrary]Lib.ConstTest
  IL_0007:  call       void [mscorlib]System.Console::WriteLine(object)
  IL_000c:  nop
  IL_000d:  ldc.i4.1
  IL_000e:  box        [TestLibrary]Lib.ConstTest
  IL_0013:  call       void [mscorlib]System.Console::WriteLine(object)
  IL_0018:  nop
  IL_0019:  ldc.i4.2
  IL_001a:  box        [TestLibrary]Lib.ConstTest
  IL_001f:  call       void [mscorlib]System.Console::WriteLine(object)
  IL_0024:  nop
  IL_0025:  ret
} // end of method Program::Main

Main函數裏的代碼,在編譯時已經將enum類型的符號:A,B,C。轉換爲數字:0,1,2。並且生成了box指令。如下:
box [TestLibrary]Lib.ConstTest 這將指令是將常量 0,1,2進行裝箱,生成枚舉類型ConstTest的對象。
因此
測試一:能夠將0,1,2裝箱和生成符號A,B,C
測試二:由於枚舉符號A不存在,因此將0,1裝箱爲B,C;而2無法裝箱,只好返回數值表示;
測試三:因爲在裝箱時無法找到枚舉類型的引用,因此報錯。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章