我如何比较两个枚举?

时间:2021-01-01 17:32:21

标签: c#

这是我的代码,

[Flags]
public enum Colors { None = 0, Red = 1, Yellow = 2, Blue = 4, Green = 8, Orange = 16, Brown = 32, Cyan = 64, Magenta = 128, Other = 256 };



class Program
{
    Colors familyRGB = Colors.Red | Colors.Blue | Colors.Green;
    Colors familyCMY = Colors.Cyan | Colors.Magenta | Colors.Yellow;
    Colors familyRYB = Colors.Red | Colors.Blue | Colors.Yellow;

我必须写一个方法,它以两个族为参数,并且做的事情很少 所以我这样做了

public static void TwoFamilyColorSystem(Colors family1, Colors family2)

我想打印系列 1 中存在但系列 2 中不存在的元素。 我怎么做? 例如,如果我使用 RGB 和 RYB,它应该打印绿色,因为绿色存在于 RGB 而不是 RYB。

3 个答案:

答案 0 :(得分:5)

~ 反转位。所以:

return (Colors)(family1 & ~family2);

答案 1 :(得分:1)

应该这样做,它将返回每个枚举值的可枚举值,该值仅属于给定的两个系列中的一个(并且恰好是一个):

public static IEnumerable<Colors> TwoFamilyColorSystem(Colors family1, Colors family2)
{
    foreach(Colors value in Enum.GetValues<Colors>())
        if(family1.HasFlag(value) && !family2.HasFlag(value))
            yield return value;
}

答案 2 :(得分:0)

由于问题 is 被标记为 ,这就是您在 Java 中的做法:

public enum Colors {
    None(0), Red(1), Yellow(2), Blue(4), Green(8), Orange(16), Brown(32), Cyan(64), Magenta(128), Other(256);

    public static final Set<Colors> familyRGB = Collections.unmodifiableSet(EnumSet.of(Red, Blue, Green));
    public static final Set<Colors> familyCMY = Collections.unmodifiableSet(EnumSet.of(Cyan, Magenta, Yellow));
    public static final Set<Colors> familyRYB = Collections.unmodifiableSet(EnumSet.of(Red, Blue, Yellow));

    private final int flag;

    private Colors(int flag) {
        this.flag = flag;
    }

    public int getFlag() {
        return this.flag;
    }

    public Set<Colors> toFamily() {
        return EnumSet.of(this);
    }

    /**
     * Return colors in {@code a} that are not in {@code b}.
     */
    public static Set<Colors> subtract(Set<Colors> a, Set<Colors> b) {
        EnumSet<Colors> c = EnumSet.copyOf(a);
        c.removeAll(b);
        return c;
    }
}

flag 值未用于此目的,可能会被删除,但保留在这里以防它用于其他目的。

测试

System.out.println(Colors.subtract(Colors.familyRGB, Colors.familyRYB));
System.out.println(Colors.subtract(Colors.familyRGB, Colors.Blue.toFamily()));

输出

[Green]
[Red, Green]
相关问题