如何重构类中重复判断OperationType枚举的冗余if-else语句
重构方案
核心思路是把每个设备对应的关联资源(目标设备实例、参数列表、XY数值存储集合)封装为独立的上下文对象,通过字典映射枚举值和对应上下文,完全消除重复判断,同时通过Flags枚举原生支持多设备并行执行。
第一步:封装设备操作上下文
将每个设备类型的专属资源和操作内聚到独立类中,避免资源散落在执行类中:
public class OperationContext { public Device TargetDevice { get; } public List<DeviceParameters> Parameters { get; } public List<double> XValues { get; } public List<double> YValues { get; } public OperationContext(Device targetDevice, List<DeviceParameters> parameters, List<double> xValues, List<double> yValues) { TargetDevice = targetDevice; Parameters = parameters; XValues = xValues; YValues = yValues; } // 清空历史存储值 public void ClearValues() { XValues.Clear(); YValues.Clear(); } // 记录当前读数 public void RecordCurrentValue(Device sharedDevice) { XValues.Add(TargetDevice.CurrentValue); YValues.Add(sharedDevice.CurrentValue); } }
第二步:改造枚举支持多选项
给OperationType加上Flags特性,支持传入多个设备类型的组合:
[Flags] public enum OperationType { None = 0, A = 1 << 0, B = 1 << 1, // 后续新增C设备直接加:C = 1 << 2,以此类推 }
第三步:重构执行类逻辑
通过字典维护枚举和上下文的映射关系,核心执行逻辑不需要再做类型判断:
public class MyOperationExecuter { public Device SharedDevice { get; } private readonly Dictionary<OperationType, OperationContext> _operationContextMap; // 构造函数注入所有依赖,初始化上下文映射 public MyOperationExecuter(Device sharedDevice, Device deviceA, List<DeviceParameters> parametersA, List<double> xValuesA, List<double> yValuesA, Device deviceB, List<DeviceParameters> parametersB, List<double> xValuesB, List<double> yValuesB) { SharedDevice = sharedDevice; _operationContextMap = new Dictionary<OperationType, OperationContext> { { OperationType.A, new OperationContext(deviceA, parametersA, xValuesA, yValuesA) }, { OperationType.B, new OperationContext(deviceB, parametersB, xValuesB, yValuesB) } // 后续新增C设备只需要在这里加一行映射即可,不需要修改核心执行逻辑 }; } public void DoMyOperation(OperationType operationType) { // 筛选出所有需要执行的设备上下文 var targetContexts = _operationContextMap .Where(kv => operationType.HasFlag(kv.Key)) .Select(kv => kv.Value) .ToList(); if (!targetContexts.Any()) return; // 清空所有目标设备的历史数值 targetContexts.ForEach(ctx => ctx.ClearValues()); // 按设备分别执行参数遍历和读数记录 foreach (var context in targetContexts) { foreach (var parameters in context.Parameters) { SharedDevice.Parameters = parameters; context.RecordCurrentValue(SharedDevice); } } Save(); } private void Save() { // 原有保存逻辑保持不变 } // 如果需要对外访问单个设备的数值,可以加对应的索引器或者get方法 public (List<double> X, List<double> Y) GetValues(OperationType type) { if (_operationContextMap.TryGetValue(type, out var ctx)) return (ctx.XValues, ctx.YValues); return default; } }
重构后的优势
- 完全消除了重复的
if-else判断,核心执行逻辑和设备类型完全解耦 - 扩展性极强:新增设备类型仅需要加枚举值、补充上下文映射两行改动,不需要修改执行逻辑
- 原生支持多设备同时执行,调用时直接传入组合值即可:
DoMyOperation(OperationType.A | OperationType.B) - 代码可维护性更高,每个设备的关联资源和操作都内聚在
OperationContext中,不会散落在整个执行类里
内容的提问来源于stack exchange,提问作者Zserbinator
相关产品推荐
相关产品推荐

