简体   繁体   中英

how to Cast string to a given Enum

how to cast string enum?

i have the code below, it gives me error when i try to assign string to levelEnum, where levelEnum is an Enumeration..

foreach (CustomProperty prop in requirementTemplate.AttributesCustomList)
{
    if (prop.Name == property)
    {
        return (CRF_DB.CRF_Requirement.LevelEnum) (prop.Value.ToString());
    }
}

Is there a way to put select Enum item by assigning value to it?

hope it is clear enough

Try the following

return (CRF_DB.CRF_Requirement.LevelEnum)Enum.Parse(
  typeof(CRF_DB.CRF_Requirement.LevelEnum), 
  prop.Value.ToString());

In order to avoid an exception you can check if the value exists within that enumeration by calling IsDefined . The TryParse method would be the optimal solution if you're using .NET 4.0.

foreach (CustomProperty prop in requirementTemplate.AttributesCustomList)
{
    if (prop.Name == property && Enum.IsDefined(typeof(LevelEnum), prop.Value))
    {
        return (LevelEnum)Enum.Parse(typeof(LevelEnum), prop.Value.ToString());
    }
}

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