How to Compare Flags in C#?

前端 未结 11 1715
我寻月下人不归
我寻月下人不归 2020-11-27 04:03

I have a flag enum below.

[Flags]
public enum FlagTest
{
    None = 0x0,
    Flag1 = 0x1,
    Flag2 = 0x2,
    Flag3 = 0x4
}

I cannot make

相关标签:
11条回答
  • 2020-11-27 04:24
    if((testItem & FlagTest.Flag1) == FlagTest.Flag1) 
    {
    ...
    }
    
    0 讨论(0)
  • 2020-11-27 04:24

    Regarding the edit. You can't make it true. I suggest you wrap what you want into another class (or extension method) to get closer to the syntax you need.

    i.e.

    public class FlagTestCompare
    {
        public static bool Compare(this FlagTest myFlag, FlagTest condition)
        {
             return ((myFlag & condition) == condition);
        }
    }
    
    0 讨论(0)
  • 2020-11-27 04:27

    For bit operations, you need to use bitwise operators.

    This should do the trick:

    if ((testItem & FlagTest.Flag1) == FlagTest.Flag1)
    {
        // Do something,
        // however This is never true.
    }
    

    Edit: Fixed my if check - I slipped back into my C/C++ ways (thanks to Ryan Farley for pointing it out)

    0 讨论(0)
  • 2020-11-27 04:32

    @phil-devaney

    Note that except in the simplest of cases, the Enum.HasFlag carries a heavy performance penalty in comparison to writing out the code manually. Consider the following code:

    [Flags]
    public enum TestFlags
    {
        One = 1,
        Two = 2,
        Three = 4,
        Four = 8,
        Five = 16,
        Six = 32,
        Seven = 64,
        Eight = 128,
        Nine = 256,
        Ten = 512
    }
    
    
    class Program
    {
        static void Main(string[] args)
        {
            TestFlags f = TestFlags.Five; /* or any other enum */
            bool result = false;
    
            Stopwatch s = Stopwatch.StartNew();
            for (int i = 0; i < 10000000; i++)
            {
                result |= f.HasFlag(TestFlags.Three);
            }
            s.Stop();
            Console.WriteLine(s.ElapsedMilliseconds); // *4793 ms*
    
            s.Restart();
            for (int i = 0; i < 10000000; i++)
            {
                result |= (f & TestFlags.Three) != 0;
            }
            s.Stop();
            Console.WriteLine(s.ElapsedMilliseconds); // *27 ms*        
    
            Console.ReadLine();
        }
    }
    

    Over 10 million iterations, the HasFlags extension method takes a whopping 4793 ms, compared to the 27 ms for the standard bitwise implementation.

    0 讨论(0)
  • 2020-11-27 04:32

    Try this:

    
    if ((testItem & FlagTest.Flag1) == FlagTest.Flag1)
    {
        // do something
    }
    
    Basically, your code is asking if having both flags set is the same as having one flag set, which is obviously false. The code above will leave only the Flag1 bit set if it is set at all, then compares this result to Flag1.

    0 讨论(0)
提交回复
热议问题