分类: 嵌入式
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)
{ ... }