Generic extension method to see if an enum contains a flag

前端 未结 8 1100
闹比i
闹比i 2021-02-01 01:56

Considering this:

[Flags]
public enum MyEnum {
    One = 1,
    Two = 2,
    Four = 4,
    Eight = 8
}

public static class FlagsHelper
{
    public static bool          


        
8条回答
  •  清歌不尽
    2021-02-01 02:38

    You can basically use your existing extension method, byt use the Enum type instead of MyEnum. The problem then is that it doesn't know the enums are flags and won't allow the & operator, so you just have to convert the enum values to numbers.

        public static bool Contains(this Enum keys, Enum flag)
        {
            if (keys.GetType() != flag.GetType())
                throw new ArgumentException("Type Mismatch");
            return (Convert.ToUInt64(keys) & Convert.ToUInt64(flag)) != 0;
        }
    

    And a unit test for good measure:

        [TestMethod]
        public void TestContains()
        {
            var e1 = MyEnum.One | MyEnum.Two;
            Assert.IsTrue( e1.Contains(MyEnum.Two) );
    
            var e2 = MyEnum.One | MyEnum.Four;
            Assert.IsFalse(e2.Contains(MyEnum.Two));
        }
    

提交回复
热议问题