有没有可能用更短、可读的代码编写下一个开关?
switch (SomeValue)
{
case "001": return DoMethod1(); break;
case "002": return DoMethod2(); break;
//etc..
}
Run Code Online (Sandbox Code Playgroud)
我在想以某种方式
Dictionary<string, Func<int>> MethodsByValue = new Dictionary<string, Func<int>>()
{
{ "001", DoMethod1 },
{ "002", DoMethod2 },
}
Run Code Online (Sandbox Code Playgroud)
并通过这样做来调用它
return MethodsByValue[SomeValue]();
Run Code Online (Sandbox Code Playgroud)
但这可能吗?或者说我的想法太离谱了。我找不到这样的东西,但话又说回来,如果可能的话,我不知道这个的关键字。
编辑:回答 Lasse V. Karlsen 的请求:
这就是我的项目中的代码的样子。在某些地方更改了名称,因为原来的名称并不重要,因为它是我的母语。
public string GetRecord420(Dictionary<DataClass, object> dictionaryName)
{
// some code here
}
public string GetRecord421(Dictionary<DataClass, object> dictionaryName)
{
// some code here
}
//(Temperary) solution with the switch statement in a wrapper:
public string GetRecordByString(string s, Dictionary<DataClass, …Run Code Online (Sandbox Code Playgroud) 我想知道这种切换用例是否合适,还是有其他替代方案(模式)?
以下是我的计划的一部分:
基础是我正在做一系列的行动
程序控制一般是按照案例的顺序逐个进行;
通常任何特定情况都没有在第一次调用中完成,我们必须等到procX returns true.(等待文书回应或行动完成);
可以跳转到特定case的(StepCurrent在采样代码中更改).
我发现这种switch- case很难维护,特别是通过改变StepCurrent直接控制流程.代码看起来很难看.
有没有更好的方法?
注意:虽然我使用的是C#,但问题可能不仅限于此.
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++;
}
Run Code Online (Sandbox Code Playgroud)