此代码段在我的程序中重复很多次,但是还有其他按钮,如按钮3和4,按钮5和6等。我想知道它是否可以优化或缩短?
if (File.Exists(name1))
{
button1.IsEnabled = false;
button1.Visibility = Visibility.Hidden;
button2.IsEnabled = true;
button2.Visibility = Visibility.Visible;
}
else
{
button1.IsEnabled = true;
button1.Visibility = Visibility.Visible;
button2.IsEnabled = false;
button2.Visibility = Visibility.Hidden;
}
}
else
{
button1.IsEnabled = true;
button1.Visibility = Visibility.Visible;
button2.IsEnabled = false;
button2.Visibility = Visibility.Hidden;
}
答案 0 :(得分:1)
无关紧要的是代码的 length 。应当避免重复的逻辑:
private void HideAndDisable(Button b)
{
b.IsEnabled = false;
b.Visibility = Visibility.Hidden;
}
private void ShowAndEnable(Button b)
{
b.IsEnabled = true;
b.Visibility = Visibility.Visible;
}
public void SomeMethod()
{
if(condition)
{
HideAndDisable(button1);
ShowAndEnable(button2);
}
else
{
HideAndDisable(button2);
ShowAndEnable(button1);
}
}
它导致代码如下: