检查标志是否包含其他标志的任何值

Pro*_*Pus 0 c# enums enum-flags

我想比较两个标志,看看它们是否有共同的值。
我希望有一个扩展方法,以便“加速”编码(我将经常在各种枚举类型上使用它)。我怎么能够?
这段代码告诉我:

运算符“&”不能应用于 enum 和 enum 类型的操作数

public enum Tag
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 4,
    Value4 = 8,
    Value5 = 16
}

public static class FlagExt
{
    public static bool HasAny(this Enum me, Enum other)
    {
        return (me & other) != 0;
    }
}

public class Program
{
    public static void Main()
    {
        Tag flag1 = Tag.Value1 | Tag.Value2 | Tag.Value3;
        Tag flag2 = Tag.Value2 | Tag.Value3 | Tag.Value4;
        
        Console.WriteLine(flag1.HasAny(flag2)); // it should returns true. flag1.HasFlag(flag2) returns false.
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过这个:

    return (((int)me) & ((int)other)) != 0;
Run Code Online (Sandbox Code Playgroud)

但它会引发错误:

无法将类型“System.Enum”转换为“int”

Lee*_*lor 5

As per this answer (How to convert from System.Enum to base integer?)

You will need to wrap this code with an exception handler or otherwise ensure that both enums hold an integer.

public static class FlagExt
{
    public static bool HasAny(this Enum me, Enum other)
    {
        return (Convert.ToInt32(me) & Convert.ToInt32(other)) != 0;
    }
}
Run Code Online (Sandbox Code Playgroud)