如何使代码更简单(if / else)

时间:2014-05-20 20:24:08

标签: c#

如何使这段代码更简单?

if (PlayersLevel > 1)
    button4.Visible = true;        
else
    button4.Visible = false;

if (PlayersLevel > 2)
    button5.Visible = true;
else
    button5.Visible = false;

好的,好的,我已经知道=)谢谢

7 个答案:

答案 0 :(得分:6)

只需将值设置为比较结果:

button4.Visible = PlayersLevel > 1;
button5.Visible = PlayersLevel > 2;

答案 1 :(得分:3)

button4.Visible = (PlayersLevel > 1);
button5.Visible = (PlayersLevel > 2);

答案 2 :(得分:3)

您不需要If语句,您将获得True / False以下

button4.Visible = PlayersLevel > 1;        
button5.Visible = PlayersLevel > 2;

答案 3 :(得分:2)

一个小的Linq封装使故意代码不能伤害。放入此扩展方法

public static void VisibleWhen( this Button button , bool visibilityState )
{
  button.Visible = visibilityState ;
}

然后你可以说:

button4.VisibleWhen( PlayersLevel > 1 ) ;
button4.VisibleWhen( PlayersLevel > 2 ) ;

答案 4 :(得分:1)

你可以使用Bool的结果。

button4.Visible = PlayersLevel > 1;        
button5.Visible = PlayersLevel > 2;

答案 5 :(得分:0)

button4.Visible = PlayersLevel > 1;
button5.Visible = PlayersLevel > 2

答案 6 :(得分:0)

另一种方法:

button4.visible = PlayersLevel > 1 ? true : false;
button5.visible = PlayersLevel > 2 ? true : false;