作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经将枚举定义为 ASP.NET MVC 应用程序模型对象的一部分。
枚举称为“ContentTypes”,看起来像这样:
public enum ContentTypes
{
[Description("News story")]
NewsStory = 1,
[Description("Article")]
Article = 2
}
现在我计划向名为“Route”的枚举项添加另一组属性。此属性将允许我将每个 ContentType 映射到可以处理它的 URL。
所以在这之后我会有:
public enum ContentTypes
{
[Description("News story")]
[Route("news/item/{URLName}")]
NewsStory = 1,
[Description("Article")]
[Route("article/item/{URLName}")]
Article = 2
}
您认为此时枚举变得过于重量级了吗?
将枚举项分解成类,然后为每个类赋予“描述”和“路线”属性会更好吗?
最佳答案
您实际上是在尝试使用 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 */ }
}
现在要真正变得有趣(并使用契约式设计方法),考虑任何内容的所有共同点并定义一个接口(interface),例如我的内容。如果这样做,您可以执行以下操作:
List<IContent> myContent;
foreach (IContent ic in myContent) ic.ToString();
关于c# - 枚举是否会变得过于臃肿?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1230845/
我是一名优秀的程序员,十分优秀!