有没有一种方法可以重构C#特有的switch语句
Is there a way to refactor a switch statement that is unique to C#?
我是C#(.NET 4.0)项目的新员工,但我来自C/C++背景。我被指示"全面改进我们的产品",并遇到了一个长达1000行的方法,该方法主要由一个包含15个案例的单个switch语句组成,每个案例大约有60行代码。
在这之前,我会保持相同的通用格式,但提取了15个函数,然后根据需要找出如何共享/指向局部变量/类数据成员。然而,我现在可以使用一系列神秘的新工具,我无法摆脱有一种"C#智能"方法可以实现这一点的感觉。
有没有一种方法可以在C#(4.0)中重构这个switch语句,而这在C++中是做不到的?
编辑:以下是经过净化和总结的代码形式:
private void DeviceRequest(List<OpRequest> currentOp, double adjTime) {
//local variables
while (/*condition*/)
{
//Some setup
//Some initialization
try
{
switch (OperationType)
{
case Setup:
//Message header setup through 'if-else' statements
//Message sending
//Many nested 'if' checks, a few less 'else's
break;
case Initiate:
//Message header setup through 'if-else' statements
//Message sending
//Many nested 'if' checks, a few less 'else's
break;
case Acquire:
//Message header setup through 'if-else' statements
//Message sending
//Many nested 'if' checks, a few less 'else's
break;
case Measure:
//Message header setup through 'if-else' statements
//Message sending
//Many nested 'if' checks, a few less 'else's
break;
case Reset:
//Message header setup through 'if-else' statements
//Message sending
//Many nested 'if' checks, a few less 'else's
break;
//12 more cases, all fairly similar.
}
}
catch (RunTimeError err)
{
//A few lines of code
}
finally
{
//Objective measure of time passage
}
}
}
enum
上的switch
通常可以被操作的Dictionary
取代。为了做好准备,每个行动都必须处理相同的输入。
如果可以将代码重构为具有相同签名的15个方法的集合,则可以将它们放入Dictionary<OpRequest,DelegateType>
中,其中DelegateType
是具有方法签名的委托。
例如,如果15种方法中的每一种都有低于的签名
private void SetupAction(double adjTime) {
...
}
void InitiateAction(double adjTime) {
...
}
你可以建立一个行动字典
private readonly IDictionary<OpRequest,Action<double>> OpActions = new Dictionary<OpRequest,Action<double>> {
{OperationType.Setup, SetupAction}
, {OperationType.Initiate, InitiateAction}
, ... // and so on
};
有了这个字典,你可以重写你的循环如下:
while (/*condition*/) {
//Some setup
//Some initialization
try {
Action<double> action;
if (OpActions.TryGetValue(opType, out action)) {
action(adjTime);
} else {
... // Report an error: unknown OpRequest
}
} catch (RunTimeError err) {
... //A few lines of code
}
finally {
... //Objective measure of time passage
}
}
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何重构类层次结构以避免菱形问题
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 为什么是0;C++中的有效语句
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 我似乎对if/else的基本语句有问题:/
- 重构开关或 if/else 语句?
- 重构模板函数中的常量表达式 if 语句
- 建议重构以下形式的 if 语句?
- 重构使用 if 语句的重复范围检查
- 重复的开关语句需要重构
- 有没有一种方法可以重构C#特有的switch语句
- 重构大型事例语句、外部语句、静态局部语句