开关盒的替代品 [英] alternatives to switch-case
问题描述
我想知道这种切换用例是否合适,还是有其他替代方法(模式)?
I want to know if this kind of switch-case usage is appropriate, or there is any other alternatives (patterns)?
以下是我程序的一部分:
the following is part of my program:
基本是我正在执行一系列操作
the basics is I am doing a sequence of actions
-
通常情况下,程序控制是按照情况的顺序进行的;
generally program control is following the sequence of case one by one;
通常,任何特定情况在其第一次调用中都没有完成,我们必须等到procX 返回
s true
。 (等待工具响应或操作完成);
usually any specific case is not finished in its first call, we have to wait until the procX return
s true
. (waiting for instrument response or action completion);
可能会跳转到特定的案例
(更改 StepCurrent
)。
jump to a specific case
is possible (changing StepCurrent
in the sampling code).
我发现了这个开关
-情况
很难维护,尤其是通过更改 StepCurrent
直接控制流。代码看起来很丑。
I found this kind of switch
-case
is hard to maintain, especially by changing the StepCurrent
to direct control flow. And code looks ugly.
有没有更好的方法?
注意:虽然我使用的是C#,但问题可能不仅限于此。
note: though I am using C#, the problem might not be limited to it.
while (true)
{
if (sig_IsExit())
{
break;
}
Thread.Sleep(500);
bRetSts = false;
switch (StepCurrent) // nSeq)
{
case 0:
bRetSts = proc0();
break;
case 1:
bRetSts = proc1();
break;
case 2:
bRetSts = proc2();
break;
case 3:
bRetSts = proc3();
break;
case 4:
...
}
if( bRetSts )
StepCurrent++;
}
推荐答案
您可以使用 Dictionary< int,Func< bool>>
,这样您的循环复杂度就会降低,请参见示例:
You can use a Dictionary<int,Func<bool>>
, with this you will have less cyclomatic complexity, see the example:
注意:我使用 Dictionary 表示可以使用任何类型作为键,例如带有名称的
string
,或枚举
。
Note: i use Dictionary to show that you can use any type as key, for example a
string
with a name, or anenum
.
Dictionary<int,Func<bool>> proc = new Dictionary<int,Func<bool>>
{
{0, proc0},
{1, proc1},
{2, proc2},
{3, proc3},
}
,然后像这样使用:
while (true)
{
if (sig_IsExit())
break;
Thread.Sleep(500);
bRetSts = false;
bRetSts = proc[StepCurrent]();
if( bRetSts )
StepCurrent++;
}
这篇关于开关盒的替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!