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

标签 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 内部返回或终止执行父方法的能力?

我知道这有点挑剔,但我觉得如果其他人需要添加额外的验证检查(他们不必担心将 return 放在各处),那么以后的可扩展性会更好) 以及将结束执行的常见行为封装在本应适用于这些情况的代码中。

最佳答案

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

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

关于c# - 从 Action<string> 中的父方法返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16545123/

相关文章:

c# - 将参数传递给 NUnit 中的 TestDelegate

c# - Kotlin通用类限制,例如C#'s “class”关键字

c# - web.config 批处理 ="false"

c# - 是否可以包装特定的类或方法并将它们分配给线程?

c# - 如何在 VB.NET 中使用以下用 C# 编写的事件/委托(delegate)?

objective-c - 通过委托(delegate)调用时无法识别协议(protocol)方法

c# - 构造函数 DI - 字段永远不会分配给,并且始终具有其默认值

c# - 如何旋转自定义移动标记(图像)GMap

c# - linq Expression<TDelegate> 赋值如何在语言语法级别上工作

swift - 协议(protocol)方法不会在另一个 View Controller 中执行