从Action <string> </string>中的父方法返回

时间:2013-05-14 13:53:48

标签: c# delegates

我正在一个执行一系列验证检查的方法中工作,如果这些检查失败,则调用Action<string>来运行一些常见的拒绝代码。设置与此类似:

public void ValidationMethod() {
    Action<string> rejectionRoutine = (rejectionDescription) => {
        // do something with the reject description
        // other common code
    };

    if (condition != requiredValue) {
        rejectionRoutine("Condition check failed");
        // I currently have to put `return` here following every failed check
    }

    // many more checks following this
}

在这个系统中,一旦检查验证失败,我就不需要验证其余部分了,我只想在Action中运行公共拒绝代码并退出方法。目前要执行此操作,我在调用return后的下一行只rejectionRoutine。我想知道是否有一种方法可以在Action内合并返回或终止父方法执行的能力?

我知道这有点挑剔,但我觉得如果其他人需要添加额外的验证检查,那么对于可扩展性来说,它会更好(他们不必担心将回报放在所有地方)以及封装在这些情况下应该是常见的代码内部结束执行的常见行为。

3 个答案:

答案 0 :(得分:7)

稍微清理代码的一种方法是将所有检查推断到集合中:

Dictionary<Func<bool>, string> checks = new Dictionary<Func<bool>, string>()
{
    {()=> condition != requiredValue, "Condition check failed"},
    {()=> otherCondition != otherRequiredValue, "Other condition check failed"},
    {()=> thirdCondition != thirdRequiredValue, "Third condition check failed"},
};

如果以特定顺序运行检查很重要(此代码具有不可预测的顺序),那么您需要使用类似List<Tuple<Func<bool>, string>>的内容。

var checks = new List<Tuple<Func<bool>, string>>()
{
    Tuple.Create<Func<bool>, string>(()=> condition != requiredValue
        , "Condition check failed"),
    Tuple.Create<Func<bool>, string>(()=> otherCondition != otherRequiredValue
        , "Other condition check failed"),
    Tuple.Create<Func<bool>, string>(()=> thirdCondition != thirdRequiredValue
        , "Third condition check failed"),
};

然后,您可以使用LINQ进行验证:

var failedCheck = checks.FirstOrDefault(check => check.Item1());
if (failedCheck != null)
    rejectionRoutine(failedCheck.Item2);

答案 1 :(得分:1)

从lambda表达式中的调用方法返回没有任何意义 (如果在方法运行完毕后调用它会怎样?)

相反,您可以将其更改为Func<string, Whatever>并返回其值:

return rejectionRoutine("Condition check failed");

答案 2 :(得分:0)

作为SLaks解决方案的替代方案,如果您的设计允许,您还可以在rejectionRoutine中抛出异常。