2

I have an asmx web service in c# and have recently discovered the very useful FlagsAttribute for enums. My declaration is as follows:

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

I then test the enum as follows:

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

However, the HasFlag part of the last line is highlighted red Cannot resolve symbol 'HasFlag' and my code wont compile. Any ideas why?

4

1 回答 1

3

Enum.HasFlag is only availible in .NET Framework 4.0 or above. If you are using .NET Framework 3.5, you could include extension method from this article to mimic the HasFlag functionality. For the sake of completness, here is the code (credit goes to the author of the article):

    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;
    }
于 2014-10-29T10:42:11.183 回答