如何在不使用goto的情况下重用开关块标签?

问题描述 投票:0回答:1

如何在没有

goto
和不必要的代码复杂度的情况下实现以下代码?

namespace Test
{
    static class Program
    {
        bool keyA = false;
        bool keyB = false;
        // ...
        static void Main(string[] args)
        {
            foreach (string arg in args)
            {
                switch (arg.ToLowerInvariant())
                {
                    case "-a":
                        if(keyA) break;
                        keyA = true;
                        // do here also what the A key requires
                        break;
                    case "-b":
                        if(keyB) break;
                        keyB = true;
                        // do here also what the B key requires
                        goto case "-a"; // key B includes the action of key A
                    // ...
                }
            }
        }
    }
}

唯一暗示的就是将代码行从键 A 复制到键 B 或使用将所有内容填充到方法中,但这看起来并不方便和紧凑。

c# switch-statement coding-style command-line-arguments goto
1个回答
0
投票

为了完成你想要的,我建议你将 switchCaseA 中的所有内容都放在一个函数中。这将允许您在 switchCaseA 和 switchCaseB 中调用此逻辑。如:

namespace Test
{
    static class Program
    {
        bool keyA = false;
        bool keyB = false;
        // ...
        static void Main(string[] args)
        {
            foreach (string arg in args)
            {
                switch (arg.ToLowerInvariant())
                {
                    case "-a":
                        if(keyA) break;
                        keyA = true;
                        ReusableMethodA();
                        break;
                    case "-b":
                        if(keyB) break;
                        keyB = true;
                        // do here also what the B key requires
                        
                        ReusableMethodA();
                    // ...
                }

            }
        }

      private static void ReusableMethodA()
      {
         //do all of your logic here:
      }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.