给定以下代码,是否有更好的方法来构造它?
foreach(Thing item in SomeRandomList)
{
bool firstCondition = CalculateBool(item, someValue);
bool secondCondition = CalculateBool(item, someOtherValue);
//General things are done...
if(firstCondition || secondCondition)
{
//semi-specific things are done...
if(firstCondition)
{
//specific things are done...
}
else
{
//specific things are done...
}
}
}
此外,如果有更多条件,即 3:
foreach(Thing item in SomeRandomList)
{
bool firstCondition = CalculateBool(item, someValue);
bool secondCondition = CalculateBool(item, someOtherValue);
//imagine as many more as you want.
bool nthCondition = CalculateBool(item, lastOtherValue);
//General things are done...
if(firstCondition || secondCondition || nthCondition)
{
//semi-specific things are done...
if(firstCondition)
{
//specific things are done...
}
else if(secondCondition)
{
//specific things are done...
}
else
{
//specific things are done...
}
}
}
最佳答案
是的:多态性。
从公共(public)基础派生Thing
(或定义所有Thing
实现的接口(interface))
否则,将条件测试代码移动到 Thing
上的方法中。
关于c# - 在循环中嵌套条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2285704/