检查单选按钮的循环性能更好
本文关键字:性能 更好 循环性 循环 单选按钮 检查 | 更新日期: 2023-09-27 18:16:50
我有 512 个单独的radio buttons
,每个都与要显示的bool
相关。
我用for loop
做了一个函数,但它使用了大量的CPU。有没有更好的方法可以做到这一点?
for (int k = 0; k < NUMWORDS_FOR_PLCTOHMI_BOOLS * 16; k++)
{
string sRadioButtonName = "radioButton_PLCtoHMI_Bool" + k.ToString();
RadioButton r = Controls.Find(sRadioButtonName, true)[0] as RadioButton;
r.Checked = KepwarearrWordtoBools_PLCtoHMI[k];
}
您可以先检索所有单选按钮,然后在内存中迭代它们,如下所示:
var radioButtons = this.Controls.OfType<RadioButton>();
for (int k = 0; k < NUMWORDS_FOR_PLCTOHMI_BOOLS * 16; k++)
{
string sRadioButtonName = "radioButton_PLCtoHMI_Bool" + k.ToString();
RadioButton r = radioButtons.Single(x => x.Name == sRadioButtonName);
r.Checked = KepwarearrWordtoBools_PLCtoHMI[k];
}
这应该更有效率。
如果控件在列表中,如何执行此操作的示例:
List<RadioButton> radioButtons = new List<RadioButton>();
//Fill the List with the controls
for (int k = 0; k < radioButtons.Count; k++)
{
radioButtons[k].Checked = KepwarearrWordtoBools_PLCtoHMI[k];
}
唯一剩下的就是填满List
.
我的建议是创建一个字典,因为它查找项目的访问时间非常快。
创建按钮时:
private Dictionary<String, RadioButton> buttons = new Dictionary<String, RadioButton>();
//Wherever you create those buttons
buttons.Add("radiobutton_PLCtoHMI_Bool" + k.toString());
//When you want to get them
for (int k = 0; k < NUMWORDS_FOR_PLCTOHMI_BOOLS * 16; k++)
{
string sRadioButtonName = "radioButton_PLCtoHMI_Bool" + k.ToString();
//You find it faster than with Controls.Find()
RadioButton r = buttons(sRadioButtonName);
r.Checked = KepwarearrWordtoBools_PLCtoHMI[k];
}
foreach (var rb in this.Controls.OfType<RadioButton>())
{
var k = rb.Name.Substring(25); // because "radioButton_PLCtoHMI_Bool" has 25 characters
int i;
if(int.TryParse(k, out i)) //if k is an integer
rb.Checked = KepwarearrWordtoBools_PLCtoHMI[i];
}
我建议逻辑反转:循环RadioButton
,我们检测是否应该检查每个ReadioButton
:
// providing that all the radio buttons are on the form;
// if they are on, say, myPanel, put myPanel instead of "this"
var rButtons = this
.Controls
.OfType<RadioButton>()
.Where(item => item.Name.StartsWith("radioButton_PLCtoHMI_Bool"));
foreach (var rb in rButtons) {
int index;
if (int.TryParse(rb.Name.SubString("radioButton_PLCtoHMI_Bool".Length), out index))
if (index >= 0 && index < KepwarearrWordtoBools_PLCtoHMI.Length)
rb.Checked = KepwarearrWordtoBools_PLCtoHMI[index];
}