开发过程中我们可能会看到这种代码
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 " ) ;
2 if ( orderState = = 1 ) { }
3 else if ( orderState = = 2 ) { }
4 else if ( orderState = = 3 ) { }
5 else
6 throw new Exception ( " no status " ) ;
这些状态可能会因为需求变更增加或者减少,维护很不方便。
换了一种写法,感觉好多了。
1
public
string
GetStatusName
(
string
status
)
2 {
3 string [ ] [ ] statusTbl = {
4 new string [ ] { " 1 " , " doing " }
5 new string [ ] { " 2 " , " finished " }
6 new string [ ] { " 3 " , " cancel " }
7 } ;
8
9 foreach ( string [ ] item in statusTbl )
10 {
11 if ( item [ 0 ] = = status ) {
12 return item [ 1 ] ;
13 }
14 }
15
16
17 }
2 {
3 string [ ] [ ] statusTbl = {
4 new string [ ] { " 1 " , " doing " }
5 new string [ ] { " 2 " , " finished " }
6 new string [ ] { " 3 " , " cancel " }
7 } ;
8
9 foreach ( string [ ] item in statusTbl )
10 {
11 if ( item [ 0 ] = = status ) {
12 return item [ 1 ] ;
13 }
14 }
15
16
17 }
增加减少状态很容易,只需要在数组里设定一下就行了。代码也很直观。