-4

我有一个检查枚举状态的嵌套 if else 语句

if ( status == enum.value1) 
{
    //Call some function 1 
}
else if ( status == enum.value2) 
{
    //call some function 2
}
else if ( status == enum.valu3 ) 
{
   call some function 3. 
}
else if ( status == enum.valu3  || status == enum.valu10) 
{
   call some function 4. 
}

我该如何重构/简化它?我不想使用 swicth 案例。

4

3 回答 3

9

Try a Dictionary. Fill it up with delegates:

Dictionary<YourEnum, Action> dict = new Dictionary<YourEnum, Action>();
dict.Add(YourEnum.value1, MyMethod1);
dict.Add(YourEnum.value2, MyMethod2);
//etc.

And then return them plus invoke them when needed:

dict[myEnumValue]();
于 2013-05-06T07:18:30.590 回答
1

If you have a large amount of options, to the point where several ifs or a switch statement is inconvenient, you could create a Dictionary with the enum type as the key and a delegate as the value.

于 2013-05-06T07:18:13.243 回答
-2

没有办法(据我所知)简化您的代码模式。这似乎没有问题,因为它已经非常简单了。

于 2013-05-06T07:17:15.397 回答