项目中需要实现这样一个功能,用winform做一个客户端软件,首页上有4个模块(通过4个panel实现),这4个模块需要通过配置来动态显示其中的一个或多个,很显然我们都知道这有2的4次方,也就是16种组合,去掉一种0的状态,也就是15种排列方式。
假设这4个模块分别为A、B、C、 D
那15种组合就是:A,B,C,D,AB,AC,AD,BC,BD,CD,ABC,ABD,ACD,BCD,ABCD
方法一:
我们把这15种排列一个一个罗列出来,这样简单明了,不会把自己绕进去,就是需要写15个if
而已,具体就不写了
方法二:
允许一定程度的if
嵌套,什么程度呢,只要不把自己绕进去就行了,我选择了这种方式。
涵盖A、AB、AC、AD这几种组合
if(A){
A.Visible = true;
A.Location = new Point(a1,a2);
if(B && !C && !D){
B.Visible = true;
B.Location = new Point(b1,b2);
}else if(!B && C && !D){
C.Visible = true;
C.Location = new Point(c1,c2);
}else if(!B && !C && D){
D.Visible = true;
D.Location = new Point(d1,d2);
}
}
涵盖B、BC、BD
if(!A && B){
B.Visible = true;
B.Location = new Point(b1,b2);
if(C && !D){
C.Visible = true;
C.Location = new Point(c1,c2);
}else if(!C && D){
D.Visible = true;
D.Location = new Point(d1,d2);
}
}
涵盖C、CD
if(!A && !B && C){
C.Visible = true;
C.Location = new Point(c1,c2);
if(D){
D.Visible = true;
D.Location = new Point(d1,d2);
}
}
D
if(!A && !B && !C && D){
D.Visible = true;
D.Location = new Point(d1,d2);
}
ABC
if(A && B && C && !D){
A.Visible = true;
A.Location = new Point(a1,a2);
B.Visible = true;
B.Location = new Point(b1,b2);
C.Visible = true;
C.Location = new Point(c1,c2);
}
ABD
if(A && B && !C && D){
A.Visible = true;
A.Location = new Point(a1,a2);
B.Visible = true;
B.Location = new Point(b1,b2);
D.Visible = true;
D.Location = new Point(c1,c2);
}
ACD
if(A && !B && C && D){
A.Visible = true;
A.Location = new Point(a1,a2);
C.Visible = true;
C.Location = new Point(b1,b2);
D.Visible = true;
D.Location = new Point(c1,c2);
}
BCD
if(!A && B && C && D){
B.Visible = true;
B.Location = new Point(a1,a2);
C.Visible = true;
C.Location = new Point(b1,b2);
D.Visible = true;
D.Location = new Point(c1,c2);
}
ABCD
if(A && B && C && D){
A.Visible = true;
A.Location = new Point(a1,a2);
B.Visible = true;
B.Location = new Point(a1,a2);
C.Visible = true;
C.Location = new Point(b1,b2);
D.Visible = true;
D.Location = new Point(c1,c2);
}
这样就相当于用了9个大判断实现了功能,又在比较容易理解的范围内。
不过我相信肯定还有更简洁易懂的方法。