Convert.ChangeType and converting to enums?

前端 未结 3 1519
臣服心动
臣服心动 2020-12-10 09:54

I got an Int16 value, from the database, and need to convert this to an enum type. This is unfortunately done in a layer of the code that knows very little abou

3条回答
  •  误落风尘
    2020-12-10 10:39

    Based on the @Peter's answer here is the method for Nullable to Enum conversion:

    public static class EnumUtils
    {
            public static bool TryParse(int? value, out TEnum result)
                where TEnum: struct, IConvertible
            {
                if(!value.HasValue || !Enum.IsDefined(typeof(TEnum), value)){
                    result = default(TEnum);
                    return false;
                }
                result = (TEnum)Enum.ToObject(typeof(TEnum), value);
                return true;
            }
    }
    

    Using EnumUtils.TryParse(someNumber, out result) becomes useful for many scenarios. For example, WebApi Controller in Asp.NET does not have default protection against invalid Enum params. Asp.NET will just use default(YourEnumType) value, even if some passes null, -1000, 500000, "garbage string" or totally ignores the parameter. Moreover, ModelState will be valid in all these cases, so one of the solution is to use int? type with custom check

    public class MyApiController: Controller
    {
        [HttpGet]
        public IActionResult Get(int? myEnumParam){    
            MyEnumType myEnumParamParsed;
            if(!EnumUtils.TryParse(myEnumParam, out myEnumParamParsed)){
                return BadRequest($"Error: parameter '{nameof(myEnumParam)}' is not specified or incorrect");
            }      
    
            return this.Get(washingServiceTypeParsed);            
        }
        private IActionResult Get(MyEnumType myEnumParam){ 
           // here we can guarantee that myEnumParam is valid
        }
    

提交回复
热议问题