这俩天看到一段代码大致如下:
try
{
EnumType type = (EnumType)Enum.Parse(typeof(EnumType),Request.QueryString[“type”],false);
switch( type )
{
case EnumType.One:
// do something
break;
case EnumType.Two:
// do something
break;
}
}
catch(Exception ex)
{
// log error.
}
从逻辑上来说没有大的问题,但是由于Enum.Parse这个函数有一个比较奇怪的地方,导致这段代码可能会无效。
在Enum.Parse函数中有这样一段:
if ((char.IsDigit(value[0]) || (value[0] == '-')) || (value[0] == '+'))
{
Type underlyingType = GetUnderlyingType(enumType);
try
{
object obj2 = Convert.ChangeType(value, underlyingType, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
}
}
所以如果querystring里面传递的是一个形如type=123的内容,则开头的那段代码不会执行任何内容并且也不会抛出异常,所以在使用Enum.Parse时需要加上:
if( type != EnumType.One && type != EnumType.Two )
{
throw new ArgumentException();
}