Use an alternative of “if” statement for checkBoxes

痴心易碎 提交于 2019-12-11 08:05:46

问题


I try to replace each "if" by a "for" or "while":

if (CheckObject1.Checked)
    XRPC.SetMemory(8184, value);
if (CheckObject2.Checked)
    XRPC.SetMemory(7848, value);
[...]
if (CheckObject20.Checked)
    XRPC.SetMemory(1800, value);

I already tried this but the problem is that I don't know how to increment the number at the end of checkBox:

int current = 8184;
int X = 1;
while (current > 1800)
{
    if (CheckObjectX.Checked) // regex?
        XRPC.SetMemory(current, value);
    X += 1;
    current -= 336;
}

I don't know if a regular expression can be used for "checkBox"... Any idea?


回答1:


If this is winforms you can use Controls.Find and LINQ:

int current = 8184;
int X = 1;
while (current > 1800)
{
    CheckBox CheckObjectX = this.Controls.Find("CheckObject"+X, true).OfType<CheckBox>().SingleOrDefault();
    if (CheckObjectX != null && CheckObjectX.Checked)
        XRPC.SetMemory(current, value);
    X += 1;
    current -= 336;
}

If they're all in the same parent control and not nested you can pass false as second parameter and replace this with the container(like myCheckBoxPanel). That could be more efficient.




回答2:


You should load all of the checkboxes in to a list and iterate through that. Or even better, load them in to a dictionary, with int as the key, and the checkbox as the value, so that they can be accessed 'out of order'.

Or as an alternative, use the Tag property of the checkbox to store an integer key, and then access them by finding the item with the matching int, possibly combined with the suggestion of using a dictionary.

There are lots of ways to solve this problem, but don't be using the variable name.



来源:https://stackoverflow.com/questions/47883307/use-an-alternative-of-if-statement-for-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!