我正在尝试为我的项目创建一个接口,并且创建了一个PSU结构,如:
public struct PSU
{
public CheckBox CallHostessButton0, CallHostessButton1,
ReadLightButton0, ReadLightButton1, ReadLightButton2, ReadLightButton3;
public PictureBox BeltLight, SmokeLight;
}
public bool AssignObjectsToPSU(PSU psu, CheckBox CallHostessBtn0, CheckBox CallHostessBtn1,
CheckBox ReadLightBtn0, CheckBox ReadLightBtn1, CheckBox ReadLightBtn2, CheckBox ReadLightBtn3,
PictureBox BeltLght, PictureBox SmokeLght)
{
try
{
Log("[Info] Assigning objects to PUS units...");
psu.CallHostessButton0 = CallHostessBtn0;
// -> In here if possible <-
psu.CallHostessButton1 = CallHostessBtn1;
psu.ReadLightButton0 = ReadLightBtn0;
psu.ReadLightButton1 = ReadLightBtn1;
psu.ReadLightButton2 = ReadLightBtn2;
psu.ReadLightButton3 = ReadLightBtn3;
psu.BeltLight = BeltLght; psu.SmokeLight = SmokeLght;
LogReport("[OK]");
return true;
}
catch
{
LogReport("[Failed]");
return false;
}
}
我需要为这些对象分配对象事件,例如:
PSU TestPSU = new PSU;
TestPSU.CallHostessButton0 = checkBox1;
TestPSU.CallHostessButton0.CheckedChanged += new EventHandler(checkBox1_CheckedChanged);
因此,我需要12个“ PSU”,并且必须为每个分配它们。像上面一样。这是我的问题:有没有简单的方法可以完成这项任务?例如:在方法或循环中?像这样:
public void AssignEvents(PSU p, CheckBox cb)
{
p.CallHostessButton0.CheckedChanged += new EventHandler(cb_CheckedChanged);
}
或在结构定义内:
psu.CallHostessButton0 = CallHostessBtn0;
psu.CallHostessButton0.CheckedChanged = += new EventHandler(CallHostessBtn0_CheckedChanged);
感谢您的帮助。 :)
答案 0 :(得分:0)
您可以将委托作为附加参数传递给AssignObjectsToPSU
public bool AssignObjectsToPSU(PSU psu, ..., EventHandler checkedChangedHandler)
{
...
psu.CheckedChanged += checkedChangedHandler;
...
}
然后您可以使用
进行调用if (AssignObjectsToPSU(psu, ..., checkBox1_CheckedChanged)) {
...
}
请确保不要在()
之后附加括号checkBox1_CheckedChanged
。
然后循环
foreach (PSU psu in myPsuList) {
if (!AssignObjectsToPSU(psu, ..., checkBox1_CheckedChanged)) {
break;
}
}