如何枚举组值? [英] How to group Enum values?

查看:143
本文介绍了如何枚举组值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何能枚举组值?结果
假设我有一个像

 公共枚举颜色枚举
{
LightBlue,
浅绿,
深绿,
黑,
白色,
LightGry,
黄色
}

现在我想要定义颜色一些群体,如:光色(LightBlue,浅绿,白色,浅灰色,黄色)和暗颜色(黑色,深绿色)。结果
所以我可以在我的代码不同的地方问组。结果
如果我没有记错我的Java的时间我就可以添加方法在Java中枚举。我认为这是不可能在C#。但也许还有其他的方式



EDIT1:当然,我可以像 IsADarkColor(颜色C)。不过,我想做到这一点,不需要额外的类,因为当我需要这个功能,我可以忘了相关的类。


解决方案

我可以用静态成员添加一个实用工具类,比如 IsADarkColor(颜色C)。不过,我想做到这一点,不需要额外的类,因为我能忘记,相关的类时,我需要这个功能。




这是当扩展方法的派上用场:

  //以里德·科普塞的命名建议
公共枚举颜色
{
LightBlue,
浅绿,
深绿,
黑,
白色,
浅灰色,
黄色
}

公共静态类颜色
{
公共静态布尔IsLightColor(此Color颜色)
{
开关(彩色){
案Color.LightBlue:
情况下C​​olor.LightGreen:
情况下C​​olor.DarkGreen:
情况下C​​olor.LightGray:
返回真;
默认:
返回FALSE;
}
}
}



只要这两个类在相同的命名空间,你可以看到静态方法,就好像它属于颜色类:

  VAR颜色=颜色。浅蓝; 
如果(color.IsLightColor()){...}



(帽尖@Abdul让我想到的扩展方法)


How can I group Enum values?
Assume I have an enum like

public enum Colors
  {
    LightBlue,
    LightGreen,
    DarkGreen,
    Black,
    White,
    LightGry,
    Yellow
  }

Now I want to define some groups of colors, e.g. the light colors (LightBlue, LightGreen, White, LightGray, Yellow) and dark colors (Black, DarkGreen).
So I can ask for groups at different places in my code.
If I remember correctly my Java time I just could add methods to the enums in Java. I think that is not possible in C#. But maybe there are other ways.

Edit1: Of course I can add a Utility class with static member like IsADarkColor(Colors c). But I would like do it without an additional class because I could forget that related class when I need that feature.

解决方案

I can add a Utility class with static member like IsADarkColor(Colors c). But I would like do it without an additional class because I could forget that related class when I need that feature.

This is when Extension Methods come in handy:

// Taking Reed Copsey's naming advice
public enum Color
{
    LightBlue,
    LightGreen,
    DarkGreen,
    Black,
    White,
    LightGray,
    Yellow
}

public static class Colors
{
    public static bool IsLightColor(this Color color)
    {
        switch(color){
            case Color.LightBlue:
            case Color.LightGreen:
            case Color.DarkGreen:
            case Color.LightGray:
            return true;
            default: 
            return false;
        }
    }
}

As long as these two classes are in the same namespace, you can see the static method as if it belonged to the Color class:

var color = Color.LightBlue;
if(color.IsLightColor()) {...}

(hat tip to @Abdul for making me think of extension methods)

这篇关于如何枚举组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆