嵌套枚举的替代方法

本文关键字:方法 枚举 嵌套 | 更新日期: 2023-09-27 18:36:39

我正在尝试创建几个这样的enums,这给出了Dropdown.Category.Subcategory的语法。但是,我一直在读到这不是一个好主意。我之所以选择这个,主要是因为我想不出任何其他方法可以根据类别的选择来选择不同的enum值,然后子类别的选择取决于基于enum值的所选enum

有没有更好的方法来创建这样的功能?我希望能够轻松识别.Category.Subcategory名称,如果此代码可读,那将是一个奖励。

只是为了说清楚,我希望能够选择Category,然后有一个适当的Subcategory选择。

public class Dropdown
{
    public enum Gifts
    {
        GreetingCards,
        VideoGreetings,
        UnusualGifts,
        ArtsAndCrafts,
        HandmadeJewelry,
        GiftsforGeeks,
        PostcardsFrom,
        RecycledCrafts,
        Other
    }
    public enum GraphicsAndDesign 
    {
        CartoonsAndCaricatures,
        LogoDesign,
        Illustration,
        EbookCoversAndPackages,
        WebDesignAndUI,
        PhotographyAndPhotoshopping,
        PresentationDesign,
        FlyersAndBrochures,
        BusinessCards,
        BannersAndHeaders,
        Architecture,
        LandingPages,
        Other
    }
}

嵌套枚举的替代方法

创建一个不能从外部继承的类,给它几个内部类,每个类都从它扩展。 然后为要表示的每个值添加静态只读变量:

public class Dropdown
{
    private string value;
    //prevent external inheritance
    private Dropdown(string value)
    {
        this.value = value;
    }
    public class Gifts : Dropdown
    {
        //prevent external inheritance
        private Gifts(string value) : base(value) { }
        public static readonly Dropdown GreetingCards =
            new Gifts("GreetingCards");
        public static readonly Dropdown VideoGreetings =
            new Gifts("VideoGreetings");
        public static readonly Dropdown UnusualGifts =
            new Gifts("UnusualGifts");
        public static readonly Dropdown ArtsAndCrafts =
            new Gifts("ArtsAndCrafts");
    }
    public class GraphicsAndDesign : Dropdown
    {
        //prevent external inheritance
        private GraphicsAndDesign(string value) : base(value) { }
        public static readonly Dropdown CartoonsAndCaricatures =
            new GraphicsAndDesign("CartoonsAndCaricatures");
        public static readonly Dropdown LogoDesign =
            new GraphicsAndDesign("LogoDesign");
        public static readonly Dropdown Illustration =
            new GraphicsAndDesign("Illustration");
    }
    public override string ToString()
    {
        return value;
    }
}

在这种情况下,每个值实际上是类型 Dropdown 的实例,因此您可以拥有接受Dropdown实例的方法的参数。 对于枚举,没有办法说,"我想接受Dropdown类中声明的任何枚举。

下面是一些示例用法:

public static void UseDropdown(Dropdown type)
{
    if (type is Dropdown.Gifts)
    {
        if (type == Dropdown.Gifts.GreetingCards)
        {
            DoStuff();
        }
    }
    else if (type is Dropdown.GraphicsAndDesign)
    {
    }
}

如果您只希望子类型在某些上下文中有效,您还可以有一个接受类型 GiftsGraphicsAndDesign 对象的参数。

可悲的是,使用此解决方案没有好方法可以switch下拉值;您只需使用if/else if链来检查值。

可能不需要使用实例字符串值(

有关没有实例字符串值的版本,请参阅第一次修订版),但能够拥有一个有意义的字符串值(或其他类型的值;您可以将整数、字节或任何内容与每个枚举值相关联)会非常有帮助。

如果保留而不被覆盖,则EqualsGetHashCode实现应该是有意义的。

如果项目应该以某种方式进行逻辑排序,例如真正的枚举,您可以实现IComparable