我完全同意 svick 的评论。在某些情况下,以下方法可能很好(但不能降低圈复杂度,通常是为了创建可插入的决策者):
public class SwitchAction{
public Func<bool> Predicate { get; set; }
public Action TheAction { get; set; }
}
public List<SwitchAction> SwitchableActions = new List<SwitchAction>();
public void InitialiseSwitchableActions()
{
SwitchableActions.AddRange(new[] {
new SwitchAction() { Predicate = () => Name.Text == string.Empty,
TheAction = () => Name.Background = Brushes.LightSteelBlue },
new SwitchAction() { Predicate = () => Age.Text == string.Empty,
TheAction = () => Age.Background = Brushes.LightSteelBlue },
});
}
public void RunSwitchables()
{
var switched = SwitchableActions.FirstOrDefault(s => Predicate());
if(switched != null)
switched.TheAction();
else
//TODO: something else.
}
当然 - 如果实际上这些操作不是互斥的,您必须稍微更改最后一个方法:
public void RunSwitchables()
{
bool runCatchAll = true;
foreach(var switched in SwitchableActions.Where(a => a.Predicate())
{
switched.TheAction();
runCatchAll = false;
}
if(runCatchAll)
//TODO: Something else.
}
这些中的任何一个都更具可读性吗?嗯……应该不会吧。