If—Else \ If-ElseIf—Else 的随想、改造

本文探讨了使用Command模式来替代传统的If-Else及If-ElseIf-Else语句的方法,通过创建一系列Command对象来简化复杂的条件判断逻辑,并展示了不同应用场景下的实现方式。

最近有一个想法,想把这些If--Else、If-ElseIf-Else,全部换成一条条的Command,然后把这个Command串起来,最后放到CommandList中把它们一锅端了。:)

所以以下就这个想法产物:

先列举一下通常的分支、支叉

static String IfElseIfElse (Int32 conditionParam) {
            var result = String.Empty;
            if ( conditionParam == 1 ) {
                result = "conditionParam1";
            }
            else if ( conditionParam == 2 ) {
                result = "conditionParam2";
            }
            else {
                result = "default";
            }
            return result;
        }

那现在就按照想法、分不同场景来进化Code吧

场景1:根据传统的If-Else进行的改造,只适用传统的True Or Else的操作

声明方法: T ExecuteCommand<T> (IDictionary<Boolean , List<Func<T>>> commandList)

具体代码:

          /// <summary>
       /// 适用传统的True Or False的操作
       /// </summary>
       static T ExecuteCommand<T> (IDictionary<Boolean , List<Func<T>>> commandList) {
           T t = default ( T );
           foreach ( var command in commandList ) {
               if ( command.Key ) {
                   t = command.Value[0] ();
                   break;
               }
               else {
                   t = command.Value[1] ();
                   break;
               }
           }
           return t;
       }

具体应用:

            /// <summary>
      /// 根据传统的If-Else进行的改造
      /// </summary>
      static String CommandList (Int32 conditionParam) {

          var commandList = new Dictionary<Boolean , List<Func<String>>> ();
          {
              commandList.Add ( ( conditionParam == 1 ) ,
                                  new List<Func<String>> (){
                                  ()=> { return  "conditionParam1"; },
                                  ()=> { return "-conditionParam1"; }
                              } );
              commandList.Add ( ( conditionParam == 2 ) ,
                                  new List<Func<String>> () {
                                  ()=> { return "conditionParam2"; }
                              } );
          }
          return ExecuteCommand<String> ( commandList );
      }

--------------------------------------------------------------------------------------------------------------------------------------------------

场景2:根据“场景1”缺点,增加了对If-ElseIf-Else的支持

声明方法: T ExecuteCommand<T> (Boolean? condition , Func<T> action)

具体代码:

          /// <summary>
       /// 适用True And False And Default的操作
       /// </summary>
       static T ExecuteCommand<T> (Boolean? condition , Func<T> action) {
           T t = default ( T );
           if ( condition.HasValue ) {
               if ( condition.Value ) { t = action (); }
           }
           else {
               t = action ();
           }
           return t;
       }

具体应用:

             /// <summary>
       /// 增加了对If-ElseIf-Else的支持
       /// </summary>
       static String CommandFuncList (Int32 conditionParam) {
           var commandList = new List<String> (){
            ExecuteCommand<String>(( conditionParam ==1 ),
                                   ()=> { return  "conditionParam1"; }
            ),
            ExecuteCommand<String>(( conditionParam ==2 ),
                                   ()=> { return "conditionParam2"; }
            ),
            ExecuteCommand<String>(null,
                                   ()=> { return "default"; }
            )
           };
           return commandList.Where ( o => o != null ).First ();
       }

--------------------------------------------------------------------------------------------------------------------------------------------------

以上场景都是带返回值,那如何对不同分支、不同那个什么;只想执行方法,一个方法或多个方法,又应该如何处理呢?

场景3:告诉我们还可以这样干

声明方法:List<Action> ExecuteCommand (Boolean? condition , List<Action> action)

具体方法:

             /// <summary>
       /// 只适用If-Else的方法操作
       /// </summary>
       static List<Action> ExecuteCommand (Boolean? condition , List<Action> action) {
           List<Action> _action = default ( List<Action> );
           if ( condition.HasValue ) {
               if ( condition.Value ) {
                   _action = action;
               }
           }
           else {
               _action = action;
           }
           return _action;
       }

具体应用:

       static void CommandActionList (Int32 conditionParam) {
            var commandList = new List<List<Action>> (){
             ExecuteCommand(( conditionParam ==1 ),
                            new List<Action>() { ()=> Write() }
             ),
             ExecuteCommand(( conditionParam ==2 ),
                            new List<Action>(){
                                  ()=> Write(),
                                  ()=> WriteAction()
                            }
             )
            };
            commandList.Where ( o => o != null ).Select ( o => o ).ToList ().ForEach ( o => o.ForEach ( i => i () ) );
        }

--------------------------------------------------------------------------------------------------------------------------------------------------

场景4:告诉我们,加上执行步骤,会让我们对分支掌控游刃有余

声明方法:List<Action> ExecuteCommand (ref Boolean execStep , Boolean? condition , List<Action> action)

具体方法:

          static List<Action> ExecuteCommand (ref Boolean execStep , Boolean? condition , List<Action> action) {
            List<Action> _action = default ( List<Action> );
            if ( execStep ) {
                if ( condition.HasValue ) {
                    if ( condition.Value ) {
                        _action = action;
                        execStep = false;
                    }

                }
                else {
                    _action = action;
                    execStep = false;
                }
            }
            return _action;
        }

具体应用:

       static void CommandActionListWithStep (Int32 conditionParam) {
            var execStep = true;
            var commandList = new List<List<Action>> (){
             ExecuteCommand(ref execStep,( conditionParam ==1 ),
                            new List<Action>() { ()=> Write() }
             ),
             ExecuteCommand(ref execStep,( conditionParam ==2 ),
                            new List<Action>(){
                                  ()=> Write(),
                                  ()=> WriteAction()
                            }
             ),
             ExecuteCommand(ref execStep,null, new List<Action>(){ ()=> WriteDefault() } )
            };

            commandList.FindAll ( (p) => { return p != null; } )
                       .ForEach ( o => o.ForEach ( i => i () ) );
        }

 

        static void Write () { Console.Write ( "Hello Command" ); }

        static void WriteAction () { Console.Write ( "Hello Action" ); }

        static void WriteDefault () { Console.Write ( "Hello Default" ); }

--------------------------------------------------------------------------------------------------------------------------------------------------

最终全部方法执行结果:

static void Main (string[] args) {
           Console.Write ( "IfElseIfElse ( 1 )" + IfElseIfElse ( 1 ) );
           Console.WriteLine ();
           Console.Write ( "IfElseIfElse ( 4 )" + IfElseIfElse ( 4 ) );
           Console.WriteLine ();
           Console.Write ( "CommandList ( 1 )" + CommandList ( 1 ) );
           Console.WriteLine ();
           Console.Write ( "CommandList ( 2 )" + CommandList ( 2 ) );
           Console.WriteLine ();
           Console.Write ( "CommandFuncList ( 1 )" + CommandFuncList ( 1 ) );
           Console.WriteLine ();
           Console.Write ( "CommandFuncList ( 4 )" + CommandFuncList ( 4 ) );
           Console.WriteLine ();
           CommandActionList ( 1 );
           Console.WriteLine ();
           CommandActionList ( 2 );
           Console.WriteLine ();
           CommandActionListWithStep ( 1 );
           Console.WriteLine ();
           CommandActionListWithStep ( 4 );
           Console.WriteLine ();
       }

image

转载于:https://www.cnblogs.com/RuiLei/archive/2010/08/27/1809883.html

### 代码随想录简介 代码随想录是一个专注于算法学习和刷题技巧分享的平台,主要面向准备技术面试的学生和技术从业者。该网站提供了丰富的算法题目分类、解题思路以及详细的代码实现[^3]。 #### 访问方式 可以通过以下链接访问代码随想录官方网站: [https://www.programmercarl.com/](https://www.programmercarl.com/) 此网站涵盖了多种数据结构与算法主题,包括但不限于数组、链表、哈希表、字符串、二叉树、回溯算法、贪心算法以及动态规划等内容。 #### 主要特点 - **系统化学习路径**:提供从基础到高级的学习路线图,帮助用户逐步掌握各类算法知识点。 - **经典题目解析**:针对LeetCode上的热门题目进行深入分析,并附带清晰易懂的代码示例[^2]。 - **专项练习模块**:例如回溯专题中的组合问题、分割问题等,均配有详尽讲解[^1]。 以下是部分核心板块概述: #### 数据结构与算法分类 | 类别 | 描述 | |------------|----------------------------------------------------------------------| | 数组 | 包含双指针法、滑动窗口等问题解决方法 | | 链表 | 提供常见操作如反转链表、删除节点等功能详解 | | 字符串 | KMP算法等相关内容待补充 | | 栈与队列 | 深入探讨其应用场景 | | 二叉树 | 细分为遍历、属性计算等多个子方向 | | 动态规划 | 覆盖背包问题、股票买卖等多种复杂场景 | ```python # 示例代码展示如何通过Python请求网页内容(仅作演示用途) import requests url = "https://www.programmercarl.com/" response = requests.get(url) if response.status_code == 200: print("成功访问代码随想录官网") else: print(f"无法访问,状态码:{response.status_code}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值