c# - 设计模式中枚举的替代方案

标签 c# .net design-patterns enums

考虑一个基础程序集 base 有一个 enum 类型的情况

public enum ItemState = { red, green, blue };

我在其他程序集 Project_1Project_2 等中使用此基础程序集。

他们每个人都做一些特定的事情,并且需要特定于项目的状态,例如 Project_1 中的 {grey, black, white, ...} Project_2 中的 {brown, transparent, ...}

Project_1 不允许使用(如果可能甚至看到){brown, transparent, ...}。同样,Project_2 不能使用 {grey, black, white, ...}

我知道“部分枚举”不存在 - 那么针对此类任务的建议设计模式是什么?

最佳答案

由于无法继承枚举,一种解决方案可能是使用具有静态常量成员的类,如下所示:

public class ItemState
{
    protected ItemState() { }

    public static ItemState red { get; } = new ItemState();
    public static ItemState green { get; } = new ItemState();
    public static ItemState blue { get; } = new ItemState();
}

然后在您的 Project_1 中,您可以派生一个自己的类:

public class ItemState_1 : ItemState
{
    public static ItemState grey { get; } = new ItemState_1();
    public static ItemState black white { get; } = new ItemState_1();
}

并且在 Project_2

public class ItemState_2 : ItemState
{
    public static ItemState brown { get; } = new ItemState_2();
    public static ItemState transparent white { get; } = new ItemState_2();
}

这可能不是最舒服的方式,但却是我目前能想到的最好的方式。

你可以这样使用它们:

ItemState project1State = ItemState_1.grey;

if (project1State == ItemState_1.grey)
   // do something

这一切都可以正常编译,但不幸的是,这些值不能用在 switch/case 语句中。这可以通过适当的 ToString() 实现来解决,字符串文字可以在 switch/case 中使用。但这当然会为这些类/属性定义添加更多代码。

关于c# - 设计模式中枚举的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38855909/

相关文章:

c# - C# 中的 H.264(或类似)编码器?

c# - 从资源写入文件,其中资源可以是文本或图像

c# - 将 List<> 转换为 Array - 我得到 "Attempted to access an element as a type incompatible with the array."

javascript - 检查 data-val-required 是否存在

c# - 为什么调用 refresh() 是一种滥用?

java - 保证只有A类才能调用B类

c# - 如何处理*许多*上下文菜单

c# - 仅当重新加载页面时,ObservableCollection 元素上的绑定(bind)才会更改

php - 我应该在 PHP 中使用 Iterator 的哪个实现,为什么?

java - 在Java中选择继承还是接口(interface)来实现设计模式?