黑马程序员技术交流社区

标题: checked关键字 [打印本页]

作者: 熊薇    时间: 2013-4-15 16:59
标题: checked关键字
本帖最后由 熊薇 于 2013-4-18 16:53 编辑
  1. enum Orientation : byte
  2. {
  3. north = 1,
  4. south,
  5. east,
  6. west
  7. }
  8. static void Main(string[] args)
  9. {
  10. Orientation myDirection;
  11. for (byte myByte = 2; myByte < 6; myByte++)
  12. {
  13. try
  14. {
  15. myDirection=checked((Orientation)myByte); //checked什么意思?
  16. if(myDirection<Orientation.north||myDirection>Orientation.west)
  17. {
  18. throw new ArgumentOutOfRangeException("myByte",myByte,
  19. "Value must be between 1 and 4");
  20. }
  21. }
  22. catch(ArgumentOutOfRangeException e)
  23. {
  24. Console.WriteLine(e.Message);
  25. Console.WriteLine("Assigning default value,Orientation.north ");
  26. myDirection = Orientation.north;
  27. }
  28. Console.WriteLine("myDirection={0}", myDirection);
  29. }
  30. }
复制代码

作者: 陈志盟    时间: 2013-4-15 17:44
checked操作符用于整型算术运算时控制当前环境中的溢出检查,就要报异常,因为checked要检查是否溢出
作者: 熊薇    时间: 2013-4-15 21:24
陈志盟 发表于 2013-4-15 17:44
checked操作符用于整型算术运算时控制当前环境中的溢出检查,就要报异常,因为checked要检查是否溢出 ...

那意思是溢出就报异常,不溢出就相当于没有checked
作者: 陈志盟    时间: 2013-4-15 21:40
熊薇 发表于 2013-4-15 21:24
那意思是溢出就报异常,不溢出就相当于没有checked

是的,溢出就会报异常。。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2