除了多个 if 语句之外,是否有更优雅的方法来为多个被选中的复选框编写逻辑? [英] Is there a more elegant way to write logic for multiple checkboxes being checked other than multiple if statements?
问题描述
我正在编写一个 Windows 窗体应用程序,它有 4 个可以同时选中的复选框.我想检查一下哪些框被选中并根据哪些框被选中做特定的逻辑.问题是,如果我最终尝试编写代码来检查复选框的每个可能组合,我将不得不编写一长串 if else 语句,而无需检查是否只检查了一个.有没有更优雅的方法来检查是否选中了多个复选框?还是我坚持使用 if-else 逻辑?
I am writing a windows forms application that has 4 check boxes that can be checked at the same time. I want to check to see what boxes are checked and do specific logic based on which boxes are checked. The issue being that if I end up trying to write code to check each possible combination of the check boxes I would have to write a long list of if else statements, and that is without checking for if there is only one checked. Is there any more elegant way to check whether or not multiple check boxes are checked? or am I stuck using if-else logic?
//This is the type of code I am trying to avoid
//check all the conditions
//check1 is a check to add keys
//check2 is to create docs
//check3 is to create keys
//check4 is to reorder keys
//createKeys() creates keywords
//createDocs() creates documents
//addKeys() adds keywords
//reorderKeys reorders the keywords
if(check1 && check2 && check3 && check4){
createKeys();
createDocs();
addKeys();
reorderKeys();
}
else if(check1 && check2 && check3){
createKeys();
createDocs();
addKeys();
}
else if(check1 && check2 && check4){
createDocs();
addKeys();
reorderKeys();
}
else if(check1 && check2){
createDocs();
addKeys();
}
else if(check1){
addKeys();
}
else if(check2 && check3 && check4){
createKeys();
createDocs();
reorderKeys();
}
else if(check2 && check4){
createDocs();
reorderKeys();
}
else if(check2){
createDocs();
}
else if(check3 && check4){
createKeys();
reorderKeys();
}
else if(check3){
createKeys();
}
else if(check4){
reorderKeys();
}
代码更新更具体
推荐答案
if/else
的替代方案是方法表.您可以创建一个字典并将所有代码作为 Action
An alternative to if/else
would be a method table. You can create a dictionary and put all code as Action
var methodTable = new Dictionary<(bool, bool, bool, bool), Action>
{
[(false, false, false, true)] = () => { /* do something */ },
[(false, false, true, false)] = () => { /* do something else */ },
[(false, false, true, true)] = SomeClassMethod,
// and so on
};
现在你可以用单行从 if/else
块中调用代码:
Now you can invoke code from if/else
block with single line:
methodTable[(check1, check2, check3, check4)].Invoke();
编辑
如果您不想处理某些复选框组合,您必须选择:
If there is some combination of checkboxes you do not want to process you have to options:
向 methodTable
添加空处理程序,例如:
Add empty handlers to methodTable
like:
[(false, false, false, true)] = () => {}, // do nothing
或者(这对我来说更好)使用 TryGetValue
方法:
Or (which is better for me) use TryGetValue
method:
if (methodTable.TryGetValue((check1, check2, check3, check4), out var method))
method.Invoke();
这篇关于除了多个 if 语句之外,是否有更优雅的方法来为多个被选中的复选框编写逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!