C# 中两个枚举值之间的按位逻辑与 (&) 运算符是否有解决方案

Is there a solution for a bitwise logical AND (&) operator between two Enum values in C#

考虑以下 C# 中的简单标志枚举:

[Flags]
public enum CountingEnum
{
    Zero = 0,
    One = 1 << 0,
    Two = 1 << 1,
    Three = Two | One,
    Four = 1 << 2,
    Five = Four | One,
}

如果我想知道一个值是否包含另一个值,我可以使用按位逻辑与 (&) 运算符编写一个简单的扩展方法。这看起来很像 Enum.HasFlag,但我写出来是有原因的。该方法需要知道枚举类型,而 HasFlag 只对匹配的枚举类型有效。我想要一个适用于各种类型的通用解决方案:

public static class CountingEnumExtensions
{
    public static bool Contains(this CountingEnum value, CountingEnum target)
    {
        return (value & target) == target;
    }
}

这有助于检查一个标志值是否包含另一个标志值的简洁语法:

if (CountingEnum.Five.Contains(CountingEnum.Four))
{
    // Yep!
}

if (CountingEnum.Four.Contains(CountingEnum.Five))
{
    // Nope!
}

但是如果我有另一个标志枚举呢?每次我想这样做时,我 可以 制作另一种扩展方法,但这不是很可持续。 .HasFlag 也没有帮助:

if (CountingEnum.Three.HasFlag(AnotherCountingEnum.One){
     // System.ArgumentException
}

我可以在任何地方手动使用它,但对于按位文盲来说,它的可读性不是很好:

if ((SomeEnum.Value & SomeEnum.Target) == SomeEnum.Target)
{
    // Dunno!
}

但是有通用的解决方案吗?当然,以下不会编译,但它传达了我想要的想法:

public static class EnumExtensions
{
    public static bool Contains(this Enum value, Enum target)
    {
        // Cannot apply operation '&' to operands of
        // type 'System.Enum' and 'System.Enum'
        return (value & target) == target;
    }
}

是否有一个通用的解决方案来对任何两个匹配类型的标志枚举值执行按位逻辑与?

如果它们的符号不重要,可以尝试将无符号整数类型转换。

public static bool Contains(this Enum value, Enum target)
{
    uint y = Convert.ToUInt32(value);
    uint z = Convert.ToUInt32(target)
    return (y & z) == z;
}