C#中不同参数类型的重复方法如何优化?
优化方案:提取通用分发逻辑
完全可以通过提取泛型通用方法消除重复代码,核心思路是把三个方法里完全一致的流程逻辑抽离出来,仅将差异部分(参数类型、对应的Execute重载调用)通过委托传入。
第一步:编写泛型通用分发方法
新增一个私有泛型方法,封装重复的判断、遍历逻辑,通过Func委托接收具体的Execute调用逻辑:
private void DispatchCommand<T>(T parameter, Func<ICommand, T, bool> executeFunc) { // 优先执行预准备命令 if (_preparedCommand != null) { executeFunc(_preparedCommand, parameter); return; } // 遍历所有命令尝试执行 foreach (var command in _commands) { if (executeFunc(command, parameter)) { return; } } }
第二步:简化原有分发方法
原来的三个方法只需调用这个通用方法,传入对应参数和Execute的调用逻辑即可:
private void DispatchGameUnitCommand(GameUnit gameUnit) { DispatchCommand(gameUnit, (cmd, unit) => cmd.Execute(unit)); } private void DispatchLocationCommand(Vector2 screenPosition) { DispatchCommand(screenPosition, (cmd, pos) => cmd.Execute(pos)); } private void DispatchShortcutCommand(string shortcut) { DispatchCommand(shortcut, (cmd, key) => cmd.Execute(key)); }
额外细节优化
原代码中的for循环替换为foreach,让代码更简洁易读,同时不会影响执行性能。
改造后,所有重复的流程逻辑都集中在DispatchCommand<T>中,后续若需修改分发规则(比如增加日志、调整执行优先级),只需修改这一个方法即可,维护性大幅提升。
内容的提问来源于stack exchange,提问作者ProtoTyPus
相关产品推荐
相关产品推荐

