【问题标题】:What is the best way to attach a label to an enum value将标签附加到枚举值的最佳方法是什么
【发布时间】:2013-05-09 22:06:37
【问题描述】:

可以说我有一个这样的枚举定义:

    public enum eCommentType
    {
        NormalComment = 0,
        OpenningComment = 1,
        StartProgressCommetn = 2,
        ClouserComment = 3,
        ReopennignComment = 4
    }

现在我想在网页上显示enum 选项。 我可以只使用switch 语句,但是当我添加一个新值时,我将不得不更新我的 switch 语句。 为每个值或事件附加标签以更好地支持多语言界面的资源 id 的最佳方法是什么?

附言 我将 MVC 用于我当前的项目,但我希望有一个通用的答案,它可以用于许多技术,即设计模式。

【问题讨论】:

标签: c# asp.net-mvc design-patterns language-agnostic enums


【解决方案1】:

to 字符串返回枚举的名称,或者您可以为每个枚举使用标签 [Description("yournamehere")] 并使用它

public enum eCommentType
{
    [Description("my super normal comment")]
    NormalComment = 0,
    [Description("my super opening comment")]
    OpenningComment = 1,
    [Description("etc")]
    StartProgressCommetn = 2,
    [Description("etc")]
    ClouserComment = 3,
    [Description("etc")]
    ReopennignComment = 4
}

【讨论】:

    【解决方案2】:

    事件更好的资源ID来支持多语言界面?

    你可以从资源中获取文本

    var text = normalComment.GetName();
    
    
    public static class EnumExtension
    {
            public static string GetName(this eCommentType type)
            {
                return Strings.ResourceManager.GetString(type.ToString());
            }
    }
    

    【讨论】:

      【解决方案3】:

      在 .net 世界中,您可以通过向枚举添加属性并实现自定义类型转换器来解决此问题,该转换器可以使用属性中的资源 id 将相应的枚举值转换为本地化文本

      这种方法与 Fabio Marcolini 提供的方法基本相同,只是自定义类型转换器将使描述本地化

      【讨论】:

        【解决方案4】:

        如果您需要向用户显示里面的项目的描述,您可以使用:

        Enum.GetValues ,点赞:

        var values = Enum.GetValues(typeof(eCommentType)); 
        

        但是,MVC 通常不仅是关于呈现,也是 UI 和模型之间的绑定,所以通常你需要将屏幕上可见的值映射实际值 em> of eCommentType enum 你必须有一些“映射器”来将一个数据转换为另一个数据。

        是的,您也可以使用相同的函数来遍历所有可用值并找到请求的值,在 get 之后它是 INT,但老实说,我会选择简单明了的 switch/case,除非枚举值数量变大。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多