简体   繁体   中英

Invalid cast from 'System.Int32' to Enum using reflections

I have a method which converts DataTable to List<T> . It was working fine until I had bit column in my MySql database. It was unable to convert bit value 1 to C# type bool . So I tried to convert it like

Convert.ChangeType(value, prop.PropertyType);

where value is something that database returned and prop in PropertyInfo where value will be assigned.

It worked fine but it broke how enums were added.

eg previously I was able to assign integer to enum field but now getting an error

Invalid cast from 'System.Int32' to 'EnumsAndConstants.QuestionType'.

I know one solution could be converting value to type only when TypeCastingException occurs but I don't want exception to occur at all. Is there any concrete solution that work for all types?

You could check prop.PropertyType.IsEnum in an if statement and use Enum.ToObject like so:

if (prop.PropertyType.IsEnum)
{
    return Enum.ToObject(prop.PropertyType, value);
}
else
{
    return Convert.ChangeType(value, prop.PropertyType);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM