简体   繁体   中英

Convert string to enum, but when enum type is only known at runtime

I am writing some code to read values from a database and convert them into an object.

My object has a few members whose type is custom defined enums.

I am trying something like this in order to convert a string variable to an enum:

var castTo = fieldInfo.PropertyType.GetType(); //returns a Type object, e.g. MyEnum
var parsedEnum = (castTo) Enum.Parse(castTo, valueFromSql);

The problem is that compiler wouldn't accept a variable that contains a Type object.

There is no problem if instead of the castTo variable I use an enum name, but it needs to be defined at runtime.

You could try that:

var castTo = fieldInfo.PropertyType.GetType(); 
var parsedEnum = Convert.ChangeType(Enum.Parse(castTo, valueFromSql), castTo);

More information about changing type can be found here: https://msdn.microsoft.com/en-us/library/system.convert.changetype(v=vs.110).aspx

There should be also a workaround for situation where database contains value that doesn't exists in your enum . Application will crash, as it will be not possible to do casting then.

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