简化检查以显示所选控件
本文关键字:控件 显示 检查 | 更新日期: 2023-09-27 18:27:27
所以我有这个代码。它的作用是在用户点击按钮时显示所选的用户控件。如果特定的用户控件已经可见,点击其按钮将隐藏它。
代码相当重复,有什么建议吗?我该如何使它更简洁?
private void changeControl(TextControl control)
{
switch (control)
{
case TextControl.TextBox:
if (IsRadTextBoxVisible == true)
{
IsRadTextBoxVisible = false;
}
else
{
IsRadTextBoxVisible = true;
}
IsCountriesListBoxVisible = false;
IsSliderFontSizeVisible = false;
IsSliderFontRotateVisible = false;
break;
case TextControl.Font:
if (IsCountriesListBoxVisible == true)
{
IsCountriesListBoxVisible = false;
}
else
{
IsCountriesListBoxVisible = true;
}
IsRadTextBoxVisible = false;
IsSliderFontSizeVisible = false;
IsSliderFontRotateVisible = false;
break;
case TextControl.Size:
if (IsSliderFontSizeVisible == true)
{
IsSliderFontSizeVisible = false;
}
else
{
IsSliderFontSizeVisible = true;
}
IsRadTextBoxVisible = false;
IsCountriesListBoxVisible = false;
IsSliderFontRotateVisible = false;
break;
case TextControl.Rotate:
if (IsSliderFontRotateVisible == true)
{
IsSliderFontRotateVisible = false;
}
else
{
IsSliderFontRotateVisible = true;
}
IsRadTextBoxVisible = false;
IsCountriesListBoxVisible = false;
IsSliderFontSizeVisible = false;
break;
default:
break;
}
}
var stateRad= IsRadTextBoxVisible;
var stateSlider = IsSliderFontRotateVisible;
var ........
var ........
IsCountriesListBoxVisible = false;
IsSliderFontSizeVisible = false;
IsSliderFontRotateVisible = false;
IsRadTextBoxVisible = false
switch (control)
{
case TextControl.TextBox:
IsRadTextBoxVisible = !stateRad
break;
case TextControl.Font:
IsCountriesListBoxVisible = !statexxx
break;
case TextControl.Size:
IsSliderFontSizeVisible = !statexxx
break;
case TextControl.Rotate:
IsSliderFontRotateVisible = !statexxx
break;
default:
break;
}
private void changeControl(TextControl control)
{
IsRadTextBoxVisible = control == TextControl.TextBox ? !IsRadTextBoxVisible : false;
IsCountriesListBoxVisible = control == TextControl.Font ? !IsCountriesListBoxVisible : false;
IsSliderFontSizeVisible = control == TextControl.Size ? !IsSliderFontSizeVisible : false;
IsSliderFontRotateVisible = control == TextControl.Rotate ? !IsSliderFontRotateVisible : false;
}
它的作用:
control == TextControl.TextBox
返回true或false。
现在,三元运算符?:在之后执行代码如果表达式在之前返回true,或之后的代码:如果表达式在之前返回错误
在这种情况下,如果控件匹配,我们将在之后执行代码,在本例中切换属性。如果控件不匹配,我们将在:之后执行代码,这将属性设置为false。
在这种情况下,我不会使用switch case,因为你不能进行复杂的布尔运算。也许您可以使用一些if-else语句来提高代码的效率。开关盒有时非常有限,不会使用它们。