如何将字符串转换为给定的枚举

发布于 2024-11-29 15:27:01 字数 351 浏览 1 评论 0原文

如何转换字符串枚举?

我有下面的代码,当我尝试将字符串分配给 levelEnum 时,它给了我错误,其中 levelEnum 是一个枚举。

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

有没有办法通过为其赋值来放置选择枚举项?

希望它足够清楚

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

黯然#的苍凉 2024-12-06 15:27:01

尝试以下操作

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

Try the following

return (CRF_DB.CRF_Requirement.LevelEnum)Enum.Parse(
  typeof(CRF_DB.CRF_Requirement.LevelEnum), 
  prop.Value.ToString());
墨落成白 2024-12-06 15:27:01

为了避免异常,您可以通过调用 IsDefined 检查该值是否存在于该枚举中。如果您使用 .NET 4.0,则 TryParse 方法将是最佳解决方案。

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());
    }
}

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());
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文