【问题标题】:Is there a point at which an Enum can get too bloated?枚举是否会变得过于臃肿?
【发布时间】:2009-08-05 02:09:34
【问题描述】:

我已将 Enum 定义为 ASP.NET MVC 应用程序的模型对象的一部分。

枚举称为“ContentTypes”,看起来像这样:

public enum ContentTypes
{
    [Description("News story")]
    NewsStory = 1,

    [Description("Article")]
    Article = 2
}

现在我计划为枚举项添加另一组属性,称为“路线”。这个属性将允许我将每个 ContentType 映射到可以处理它的 URL。

所以在此之后我将拥有:

public enum ContentTypes
{
    [Description("News story")]
    [Route("news/item/{URLName}")]
    NewsStory = 1,

    [Description("Article")]
    [Route("article/item/{URLName}")]
    Article = 2
}

你是否认为枚举在这一点上变得太重了?

将枚举项分解为类,然后给每个类一个“Description”和“Route”属性会更好吗?

【问题讨论】:

    标签: c# asp.net-mvc linq-to-sql enums model


    【解决方案1】:

    您实际上是在尝试使用 Enum 来区分 Content 对象的多个变体,而无需实际创建 Content 对象的多个版本。

    您的应用程序的行为将取决于 Enum 的设置,这是一个不错的选择。例如,您可能有类似的内容:

    public Content
    {
        private ContentTypes contentType;
        public string ToString()
        {
            switch (contentType)
            ...
        }
    }
    

    从可维护性的角度来看,这会让您发疯。考虑改为使用继承来获得您所追求的行为:

    public Content
    {
        public abstract string ToString();
    }
    
    public NewsStory : Content
    {
        public override string ToString() { /* Appropriate formatting of output */ }
    }
    
    public Article : Content
    {
        public override string ToString() { /* Appropriate formatting of output */ }
    }
    

    现在要真正花哨(并使用按合同设计的方法),请考虑任何内容的所有共同点并定义一个界面,例如内容。如果这样做,您可以执行以下操作:

    List<IContent> myContent;
    foreach (IContent ic in myContent) ic.ToString();
    

    【讨论】:

      【解决方案2】:

      就个人而言,我认为枚举应该保持简单。在不仅仅是助记符的地方,我会考虑 Fowler 的“用状态/策略模式替换类型代码”。

      所以,是的,我会转换为类。

      【讨论】:

        【解决方案3】:

        您可以组合您的属性,使其看起来更像这样:

        [Description("x"), Route("y")] 
        

        如果您认为语法看起来更好。但我同意 Mitch 的观点,这些作为类可能会做得更好,特别是如果您将来可能需要添加另一个属性。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-11-23
          • 1970-01-01
          • 2015-03-17
          • 1970-01-01
          • 1970-01-01
          • 2011-03-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多