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,这句怎么能通过?没有明白,希望有人能够指导.

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值