未能在枚举上使用FlagsAttribute(无法解析符号' HasFlag')

时间:2014-10-29 10:20:58

标签: c# enums bit-manipulation flags bitflags

我在c#中有一个asmx web服务,并且最近发现了对枚举非常有用的FlagsAttribute。我的声明如下:

[Flags] 
public enum eAdPriority
{
    None = 0,
    Gold = 1,
    Silver = 2,
    Homepage = 4
}

然后我按如下方式测试枚举:

eAdPriority test = eAdPriority.Gold | eAdPriority.Homepage | eAdPriority.Silver;
test.HasFlag(eAdPriority.Gold);

但是,最后一行的HasFlag部分突出显示为红色无法解析符号'HasFlag',我的代码将无法编译。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

Enum.HasFlag仅适用于.NET Framework 4.0或更高版本。如果您使用的是.NET Framework 3.5,则可以在this article中包含扩展方法以模仿HasFlag功能。为了完整性,这里是代码(归功于文章的作者):

    public static bool HasFlag(this Enum variable, Enum value)
    {
        // check if from the same type.
        if (variable.GetType() != value.GetType())
        {
            throw new ArgumentException("The checked flag is not from the same type as the checked variable.");
        }

        Convert.ToUInt64(value);
        ulong num = Convert.ToUInt64(value);
        ulong num2 = Convert.ToUInt64(variable);

        return (num2 & num) == num;
    }