BUG吗?虫虫吗?

实在不好意思,今天才发现博客园电子期刊第一期.马上下了一个回来拜读.相见恨晚呀.
篇篇精彩,一个也没有错过.

但是我在看这篇文章<<关于枚举的种种>>时,发现一个小错误.请看文章中的一段代码:

 

// Code #13
// See Code #01 for Alignment.
public static void Main()
{
      IConvertible ic 
= (IConvertible)Alignment.Center;
      
int i = ic.ToInt32(null);
      Console.WriteLine(
"The value of Alignment.Center is {0}.", i);
}


// Output:
// The value of Alignment.Center is 1.

 

这段代码编译会出错误.系统是无法将类型“Alignment”转换为“System.IConvertible”
我们都知道枚举是值类型,枚举的父类是System.Enum,它是一个抽象类.引用类型.
它实现了3个接口IConvertible,IComparable, IFormattable

所以我认为正确代码:

IConvertible ic = (System.Enum)Alignment.Center;
int i = ic.ToInt32(null);
Console.WriteLine(
"The value of Alignment.Center is {0}.", i);

 

说明:应该把枚举先装箱为它的父类,再调用父类的接口方法.
同时我用.net reflector看了IL代码,证明我的想法是正确的.
.method private hidebysig static void Main(string[] args) cil managed
{
      .custom instance void [mscorlib]System.STAThreadAttribute::.ctor()
      .entrypoint
      // Code Size: 32 byte(s)
      .maxstack 2
      .locals (
            [mscorlib]System.IConvertible convertible1,
            int32 num1)
      L_0000: ldc.i4.1
      L_0001: box ConsoleApplication1.Alignment
      L_0006: stloc.0
      L_0007: ldloc.0
      L_0008: ldnull
      L_0009: callvirt instance int32 [mscorlib]System.IConvertible::ToInt32([mscorlib]System.IFormatProvider)
      L_000e: stloc.1
      L_000f: ldstr "The value of Alignment.Center is {0}."
      L_0014: ldloc.1
      L_0015: box int32
      L_001a: call void [mscorlib]System.Console::WriteLine(string, object)
      L_001f: ret
}

但是我看它转化后的C#代码:
private static void Main(string[] args)
{
      IConvertible convertible1 = Alignment.Center;
      int num1 = convertible1.ToInt32(null);
      Console.WriteLine("The value of Alignment.Center is {0}.", num1);
}

说明:IConvertible convertible1 = Alignment.Center,这句怎么能通过?没有明白,希望有人能够指导.

最后祝福博客园电子期刊红火起来.
"质量第一"是我们出刊的中心原则,希望质量能更上一层楼.

 

 

posted @ 2005-01-11 11:26  aierong  阅读(1229)  评论(4编辑  收藏  举报