How do I determine if an Enum value has one or more of the values it's being compared with?

后端 未结 8 1543
死守一世寂寞
死守一世寂寞 2021-01-04 07:53

I\'ve got an Enum marked with the [Flags] attribute as follows:

[Flags]
public enum Tag : int
{
    None = 0,
    PrimaryNav = 1,
    HideChildPages = 2,
            


        
相关标签:
8条回答
  • 2021-01-04 08:05

    You can do that by combining values with | and checking via &.

    To check if the value contains either of the tags:

    if ((myValue & (Tag.PrimaryNav | Tag.HomePage)) != 0) { ... }
    

    The | combines the enums you're testing (bitwise) and the & tests via bitwise masking -- if the result isn't zero, it has at least one of them set.

    If you want to test whether it has both of them set, you can do that as well:

    Tag desiredValue = Tag.PrimaryNav | Tag.HomePage;
    if ((myValue & desiredValue) == desiredValue) { ... }
    

    Here we're masking off anything we don't care about, and testing that the resulting value equals what we do care about (we can't use != 0 like before because that would match either value and here we're interested in both).

    Some links:

    • The & Operator
    • The | Operator
    0 讨论(0)
  • 2021-01-04 08:07

    You can use this extension method on enum, for any type of enums:

    public static bool IsSingle(this Enum value)
        {
            var items = Enum.GetValues(value.GetType());
            var counter = 0;
            foreach (var item in items)
            {
                if (value.HasFlag((Enum)item))
                {
                    counter++;
                }
                if (counter > 1)
                {
                    return false;
                }
            }
            return true;
        }
    
    0 讨论(0)
  • 2021-01-04 08:10

    You can use the HasFlag Method to avoid the need for the boolean logic,

    Tag Val = (Tag)9;
    
    if (Val.HasFlag(Tag.PrimaryNav))
    {
        Console.WriteLine("Primary Nav");
    }
    
    if(Val.HasFlag(Tag.HomePage))
    {
        Console.WriteLine("Home Page");
    }
    
    0 讨论(0)
  • 2021-01-04 08:11
    var someEnumValue = Tag.PrimaryNav | Tag.HomePage;
    

    To test if the enum contains a given value:

    if ((someEnumValue & Tag.PrimaryNav) == Tag.PrimaryNav)
    {
    
    }
    
    0 讨论(0)
  • 2021-01-04 08:14

    For bitwise (Flags) enums, an "any of" test is != 0, so:

    const Tag flagsToLookFor = Tag.PrimaryNav | Tag.HomePage;
    if ((node.Tag & flagsToLookFor) != 0) {
        // has some cross-over with PrimaryNav or HomePage (and possibly others too) 
    }
    
    0 讨论(0)
  • 2021-01-04 08:22

    That's a classic Extension method:

        public static bool HasFlag(this Enum val, Enum t)
        {
                return (Convert.ToUInt64(val) & Convert.ToUInt64(t)) != 0;
        }
    
    0 讨论(0)
提交回复
热议问题