从Action中的父方法返回

本文关键字:方法 返回 Action string | 更新日期: 2023-09-27 18:13:44

我正在执行一系列验证检查的方法内部工作,如果这些检查中的任何一个失败,它会调用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内部返回或终止父方法执行的能力?

我知道这有点挑剔,但我觉得如果其他人需要添加额外的验证检查(他们不必担心到处都是返回),以及将结束执行的常见行为封装在代码中,这对这些情况来说是很常见的,那么这对进一步的可扩展性来说是更好的。

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

清理代码的一种方法是将所有签出的内容外推到一个集合中:

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);

在lambda表达式中从调用者方法返回没有任何意义。
(如果在方法完成运行后调用它呢?)

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

return rejectionRoutine("Condition check failed");

作为SLaks解决方案的另一种选择,如果您的设计允许,您还可以在rejectionRoutine中抛出异常。