有没有解决方法如何简化此代码?我只想在几个相同类型的对象中设置相同的属性。这些对象是Windows 8应用程序中的TextBoxes。我认为这可能是Array和foreach的事情......但我不确定 感谢
private void makeVisible(int x)
{
if (x == 1)
{
field2.Visibility = Visibility.Visible;
field3.Visibility = Visibility.Visible;
field4.Visibility = Visibility.Visible;
field6.Visibility = Visibility.Visible;
field8.Visibility = Visibility.Visible;
field9.Visibility = Visibility.Visible;
field11.Visibility = Visibility.Visible;
}
if (x == 0)
{
field2.Visibility = Visibility.Collapsed;
field3.Visibility = Visibility.Collapsed;
field4.Visibility = Visibility.Collapsed;
field6.Visibility = Visibility.Collapsed;
field8.Visibility = Visibility.Collapsed;
field9.Visibility = Visibility.Collapsed;
field11.Visibility = Visibility.Collapsed;
errorReporter.Visibility = Visibility.Collapsed;
}
}
答案 0 :(得分:1)
你至少可以做的是:
var visibility = x == 0 ? Visibility.Collapsed : Visibility.Visible;
field2.Visibility = visible;
field3.Visibility = visible;
// etc
如果您想使用数组,您甚至可以执行以下操作,但我不确定这是否有所改进:
foreach (var obj in new[] { field1, field2, field3 ... })
{
obj.Visibility = x == 0 ? Visibility.Collapsed : Visibility.Visible;
}
答案 1 :(得分:0)
private void makeVisible(int x)
{
var boxes = new TextBox[] { field2, field3... };
foreach (TextBox box in boxes)
{
box.Visibility = (x == 1) ? Visibility.Visible : Visibility.Collapsed;
}
if (x == 0)
{
errorReporter.Visibility = Visibility.Collapsed;
}
}
答案 2 :(得分:0)
List<MyFieldType> fields=new List<MyFieldType> {field2, field3, field4, field6, field8, field9, field11};
foreach(MyFieldType field in fields)
{
if(x==1)
{
field.Visibility=Visibility.Visible;
}
else if(x==0)
{
field.Visibility=Visibility.Collapsed;
}
}
使用集合存储对象并迭代它。
答案 3 :(得分:-1)
您肯定需要按照上面的解决方式遍历这些元素,但您不必手动构建列表,使用Reflection
来简化此操作:
this.GetType().GetProperties().Where(pi=>pi.PropertyType == typeof(TextBox))