gpt4 book ai didi

c# - 枚举是否会变得过于臃肿?

转载 作者:行者123 更新时间:2023-11-30 19:14:13 25 4
gpt4 key购买 nike

我已经将枚举定义为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com