Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2313801
  • 博文数量: 527
  • 博客积分: 10343
  • 博客等级: 上将
  • 技术积分: 5565
  • 用 户 组: 普通用户
  • 注册时间: 2005-07-26 23:05
文章分类

全部博文(527)

文章存档

2014年(4)

2012年(13)

2011年(19)

2010年(91)

2009年(136)

2008年(142)

2007年(80)

2006年(29)

2005年(13)

我的朋友

分类: 嵌入式

2012-03-15 18:39:10

这是语言标准所保证的, 在产品代码中看到:

try

{

     someEnumVariable = (TheEnumType) (int_variable_in_parameter_comes_from_caller);

}

catch(Exception ex)

{

     Log.Error(" invalid typpe " +int_variable_in_parameter_comes_from_caller);

}

 

这样的catch永远不会发生, 若需要检测未定义的enum值, 可以用 Enum.IsDefined, 但要注意这个方法会抛出 ArgumentException异常:

public enum X : byte

{

   a = 0

}

 

int x = 0;

Enum.IsDefined( typeof(TheEnumType), x );

错误信息是:

System.ArgumentException: Enum underlying type and the object must be same type or object must be a String. Type passed
in was 'System.Int32'; the enum underlying type was 'System.Byte'.

 

正确的做法是:

TheEnumType e = (TheEnumType) x;

if ( Enum.IsDefined( typeof(TheEnumType), e) == false)

{  ... }

阅读(1202) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~