Switch on Enum (with Flags attribute) without declaring every possible combination?

后端 未结 9 2212
忘掉有多难
忘掉有多难 2021-01-31 14:15

how do i switch on an enum which have the flags attribute set (or more precisely is used for bit operations) ?

I want to be able to hit all cases in a switch that matche

9条回答
  •  眼角桃花
    2021-01-31 14:47

    How about this. Of course the arguments and return types of DoSomething, etc., can be anything you like.

    class Program
    {
        [Flags]
        public enum CheckType
        {
            Form = 1,
            QueryString = 2,
            TempData = 4,
        }
    
        private static bool DoSomething(IEnumerable cln)
        {
            Console.WriteLine("DoSomething");
            return true;
        }
    
        private static bool DoSomethingElse(IEnumerable cln)
        {
            Console.WriteLine("DoSomethingElse");
            return true;
        }
    
        private static bool DoWhatever(IEnumerable cln)
        {
            Console.WriteLine("DoWhatever");
            return true;
        }
    
        static void Main(string[] args)
        {
            var theCheckType = CheckType.QueryString | CheckType.TempData;
            var checkTypeValues = Enum.GetValues(typeof(CheckType));
            foreach (CheckType value in checkTypeValues)
            {
                if ((theCheckType & value) == value)
                {
                    switch (value)
                    {
                        case CheckType.Form:
                            DoSomething(null);
                            break;
                        case CheckType.QueryString:
                            DoSomethingElse(null);
                            break;
                        case CheckType.TempData:
                            DoWhatever(null);
                            break;
                    }
                }
            }
        }
    }
    

提交回复
热议问题