【问题标题】:C# Enum with description not working [duplicate]带有描述的C#枚举不起作用[重复]
【发布时间】:2011-04-26 17:25:15
【问题描述】:

可能重复:
Get Enum from Description attribute

大家好, 我有和 Enum 这样定义的。

public enum SomeType {
        [Description("One Value")]
        One,
        [Description("Two Value")]
        Two,
        [Description("Three Value")]
        Three       
    }

但是当我尝试解析这样的字符串时

SomeType  test =  (SomeType )Enum.Parse(typeof(SomeType ), "Three Value");

我收到异常“未找到请求的值‘三值’”。这不应该工作吗?

谢谢

【问题讨论】:

标签: c# enums


【解决方案1】:

不,不是。您可以通过枚举名称(“一”、“二”、“三”)找到枚举,但不能通过描述(至少不是这样)。也许通过反射......

你可能想看看这个:How to get C# Enum description from value?

更新

看看@KIvanov 的评论,看看这里:Get Enum from Description attribute

【讨论】:

  • 实际上 Parse 应该识别名称(“三”)。但不是描述。
  • 我已经编辑了我的答案。我写了“不能”,但这是一个错字。
【解决方案2】:

据我所知

SomeType  test =  (SomeType )Enum.Parse(typeof(SomeType ), "Three");

做你想做的事

【讨论】:

  • 不是真的,OP 想要通过描述而不是名称来获取枚举。顺便说一句,我没有投反对票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-12
  • 1970-01-01
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
相关资源
最近更新 更多