C#委托与params

PM *_*tra 2 c# delegates action

我有一个调用其他工具的验证方法:

public ValidationResult Validate(Some arg) {
    var errors = new List<ValidationError>();

    validate1(arg, errors);
    if (errors.Count > 0) {
        return ValidationResult.Failed(errors);
    }

    validate2(arg, other, errors);
    if (errors.Count > 0) {
        return ValidationResult.Failed(errors);
    }

    validate3(arg, other2, errors);
    if (errors.Count > 0) {
        return ValidationResult.Failed(errors);
    }

    return ValidationResult.Succeess();
}
Run Code Online (Sandbox Code Playgroud)

我想要一些方法来制作如下代码,使用for循环来调用每个验证器:

public ValidationResult Validate(Some arg) {
    var errors = new List<ValidationError>();

    var validators = new [] {
        validate1(arg, errors),
        validate2(arg, other, errors),
        validate3(arg, other2, errors)
    };

    foreach (var validator in validators) {
        validator.invoke();
        if (errors.Count > 0) {
            return ValidationResult.Failed(errors);
        }
    }

    return ValidationResult.Success();
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

tym*_*167 7

你可以试试这个

var validators = new Action[]  {
    ()=>validate1(arg, errors),
    ()=>validate2(arg, other, errors),
    ()=>validate3(arg, other2, errors)
};

foreach (var v in  validators)
    v();
Run Code Online (Sandbox Code Playgroud)