如何减少IF 子句

开发过程中我们可能会看到这种代码

1 int orderState = 3;
2 if(orderState == 1){}
3 else if(orderState == 2){}
4 else if(orderState == 3){}
5 else
6     throw new Exception("no status");

 

这些状态可能会因为需求变更增加或者减少,维护很不方便。

换了一种写法,感觉好多了。

public string GetStatusName(string status)
{
    string[][] statusTbl = {
        new string[]{"1","doing"}
        new string[]{"2","finished"}
        new string[]{"3","cancel"}
    };
   
    foreach(string[] item in statusTbl)
10     {
11         if(item[0]== status){
12             return item[1];
13         }
14     }
15
16
17 }

增加减少状态很容易,只需要在数组里设定一下就行了。代码也很直观。

posted @ 2009-11-05 10:30  疯流成性  阅读(494)  评论(0编辑  收藏  举报