我正在尝试为标志样式枚举编写一些通用的扩展方法。从C#7.3开始,TFlag类型参数可以标记为Enum,但是编译器对表达式flags & flagToTest抛出错误,它表示“运算符'&'不能应用于TFlag和TFlag类型”。由于TFlag是一个Enum,因此'&'运算符应该可以正常工作。

public static bool IsSet<TFlag>(this TFlag flags, TFlag flagToTest) where TFlag : Enum
{
    if (!Attribute.IsDefined(typeof(TFlag), typeof(FlagsAttribute)))
        throw new InvalidOperationException("The given enum type is not decorated with Flag attribute.");

    if (flagToTest.Equals(0))
        throw new ArgumentOutOfRangeException(nameof(flagToTest), "Value must not be 0");

    return (flags & flagToTest) == flagToTest;
}

最佳答案

首先,看看这个答案https://stackoverflow.com/a/50219294/6064728
您可以通过这种方式或类似的方式编写函数:

public static bool IsSet<TFlag>(this TFlag flags, TFlag flagToTest) where TFlag : Enum
{
    if (!Attribute.IsDefined(typeof(TFlag), typeof(FlagsAttribute)))
        throw new InvalidOperationException("The given enum type is not decorated with Flag attribute.");

    if (flagToTest.Equals(0)) throw new ArgumentOutOfRangeException(nameof(flagToTest), "Value must not be 0");
    int a = Convert.ToInt32(flags);
    int b = Convert.ToInt32(flagToTest);
    return (a & b) == b;
}

10-04 21:35