You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用goto复用switch语句块标签并避免冗余?

解决方案

要实现需求中的逻辑,同时避免goto和不必要的复杂度,封装重复逻辑到独立方法是最清晰且紧凑的方案——既不会复制代码,也能让职责划分更明确,后续维护也更方便。

优化后的代码

namespace Test
{
    static class Program
    {
        private static bool keyA = false;
        private static bool keyB = false;

        static void Main(string[] args)
        {
            foreach (string arg in args)
            {
                switch (arg.ToLowerInvariant())
                {
                    case "-a":
                        ExecuteKeyAActions();
                        break;
                    case "-b":
                        if (!keyB)
                        {
                            keyB = true;
                            // 执行Key B专属的操作
                            ExecuteKeyAActions();
                        }
                        break;
                    // 其他case逻辑...
                }
            }
        }

        /// <summary>
        /// 封装Key A的核心操作逻辑
        /// </summary>
        private static void ExecuteKeyAActions()
        {
            if (!keyA)
            {
                keyA = true;
                // 执行Key A专属的操作
            }
        }
    }
}

另一种紧凑写法(不额外封装方法)

如果不想新增方法,也可以调整逻辑流程复用代码块,这种写法更紧凑,适合简单场景:

namespace Test
{
    static class Program
    {
        private static bool keyA = false;
        private static bool keyB = false;

        static void Main(string[] args)
        {
            foreach (string arg in args)
            {
                bool runAActions = false;
                switch (arg.ToLowerInvariant())
                {
                    case "-b":
                        if (!keyB)
                        {
                            keyB = true;
                            // 执行Key B专属的操作
                            runAActions = true;
                        }
                        break;
                    case "-a":
                        runAActions = true;
                        break;
                    // 其他case逻辑...
                }

                if (runAActions && !keyA)
                {
                    keyA = true;
                    // 执行Key A专属的操作
                }
            }
        }
    }
}

两种方案都完全避免了goto,且没有引入多余复杂度。方法封装的方案更符合代码规范,适合长期维护;第二种写法则更简洁,适合逻辑简单的场景。

内容的提问来源于stack exchange,提问作者ng256

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 07:45:15