为防止代码重复,我正在为此寻找解决方案:
private void sensor1SetUnits(string newUnit)
{
foreach (Control ctrl in groupBoxSensor1.Controls)
{
// initialize all labels
if (ctrl is Label)
{
((Label)ctrl).Text = newUnit;
}
}
}
private void sensor2SetUnits(string newUnit)
{
foreach (Control ctrl in groupBoxSensor2.Controls)
{
// initialize all labels
if (ctrl is Label)
{
((Label)ctrl).Text = newUnit;
}
}
}
private void uiInitControls()
{
sensor1SetUnits(units.celsius);
sensor2SetUnits(units.celsius);
}
但是,我有超过10个分组,我需要每次将所有标签更改为另一个单元。
我希望这样的事情:
private void uiSensorChangeUnits(Control * ptrCtrl)
{
foreach (Control ctrl in ptrCtrl)
{
// initialize all labels
if (ctrl is Label)
{
((Label)ctrl).Text = units.celsius;
}
}
}
private void someFunction()
{
uiSensorChangeUnits(&groupBoxSensor1.Controls);
uiSensorChangeUnits(&groupBoxSensor2.Controls);
}
答案 0 :(得分:2)
您可以将GroupBox传递给方法,然后使用OfType extension
来减少查找相应的控件private void SetSensorUnitLabels(GroupBox currentGB, string newUnit)
{
foreach (Label ctrl in currentGB.Controls.OfType<Label>())
{
ctrl.Text = newUnit;
}
}
SetSensorUnitLabels(groupBoxSensor1, units.celsius);
SetSensorUnitLabels(groupBoxSensor2, units.celsius);
答案 1 :(得分:1)
好人LINQ是你最好的选择。
private void Form1_Load(object sender, EventArgs e)
{
UpdateChildrenInGroupBox<Label>("Test Label");
UpdateChildrenInGroupBox<TextBox>("Test Textbox");
//Wont compile
//UpdateChildrenInGroupBox<Rectangle>("Test Rectangle");
}
private void UpdateChildrenInGroupBox<T>(string value) where T: Control
{
var allGBs = this.Controls.OfType<GroupBox>();
var allControlsInGBs = allGBs.SelectMany(f => f.Controls.Cast<Control>());
allControlsInGBs.OfType<T>().ToList().ForEach(f => f.Text = value);
}
我们循环遍历Form的所有控件,它具有Type GroupBox。然后我们选择控件并将其投射到它们。然后我们得到传递的Type并设置它们的值。
答案 2 :(得分:0)
private void UpdateUnitLabels(GroupBox groupBox, string unit)
{
foreach (Control control in groupBox.Controls)
{
var label = control as Label;
if (Label != null)
{
label.Text = unit;
}
}
}