将相同的特性设置为多个相同的对象(不要重复)
本文关键字:对象 设置 | 更新日期: 2023-09-27 18:19:54
有什么解决方案可以简化这段代码吗?我只想在几个相同类型的对象中设置相同的属性。这些对象是Windows 8应用程序中的文本框。我想可能是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;
}
}
您至少可以做以下事情:
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;
}
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;
}
}
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;
}
}
使用集合存储对象并对其进行迭代。
您肯定需要遍历上面回答的元素,但您不必手动构建列表,使用Reflection
来简化它:
this.GetType().GetProperties().Where(pi=>pi.PropertyType == typeof(TextBox))