簡體   English   中英

C#委托與params

[英]C# delegate with params

我有一個調用其他工具的驗證方法:

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

我想要一些方法來制作如下代碼,使用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();
}

我該怎么做?

你可以試試這個

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

foreach (var v in  validators)
    v();

您可以為驗證器定義公共接口,並為每個用例實現一個類。

public interface IValidator {
    ValidationResult Invoke();
}

public class Validator1 : IValidator {
    private string _arg;
    private List<ValidationError> _errors;

    Validator1(string arg, List<ValidationError> errors) {
        _arg = arg; 
       _errors = errors
    }

    public ValidationResult Validate() {
        if (_errors.Count > 0) {
            return ValidationResult.Failed(_errors);
        }
        return ValidationResult.Success();
    }
}

然后,您可以使用IValidator實例列表。

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

    var validators = new IValidator[] {
        new Validator1(arg, errors),
        new Validator2(arg, other, errors),
        new Validator3(arg, other2, errors)
    };

    foreach (var validator in validators) {
        var result = validator.Invoke();
        if (result != ValidationResult.Success()) {
            return result;
        }
    }

    return ValidationResult.Success();
}

好吧,我考慮以類似Fluent的風格實現驗證:

public interface IValidator<T>
{
    IEnumerable<ValidationError> Validate(T obj);
    IEnumerable<ValidationError> ValidateAll(IEnumerable<T> obj);
}


public class SomeTypeValidator : IValidator<SomeType>
{
    private readonly IValidator<SomeNestedType> _validator1;
    public SomeTypeValidator(IValidator<SomeNestedType> validator1)
    {
        _validator1 = validator1;
    }

    public IEnumerable<ValidationError> Validate(SomeType obj)
    {
        yield return Error("My first error");
        foreach(var e in _validator1.Validate(obj.val1))
        {
             yield return e;
        }
        /*whatever you desire goes here*/
    }

    public IEnumerable<ValidationError> ValidateAll(IEnumerable<SomeType> objs)
    {
        return objs.SelectMany(Validate);
    }
}

然后一些有用的擴展:

public static void ThrowIfInvalid(this IEnumerable<ValidationError> errors)
{
    if(errors == null)
       return;
    var e = errors.ToList();
    if(e.Any())
    {
        throw new Exception(\*use 'e' here to form exception*\);
    }
}

然后代碼中的某處我稱之為:

_validator.Validate(new SomeType()).ThrowIfInvalid();

通過這種方式,您可以將自己從這些錯誤列表/包中解脫出來,並將驗證錯誤流重定向到您想要的任何其他驗證器。 此外,您始終可以通過調用yield break來停止驗證,並且可以從它們創建ansamble。

謝謝@ tym32167!

我還有一些關於異步的補充:

        var validations = new Func<Task>[]
        {
            async () => await ValidateAsync(arg, other, errors)
        };

        foreach (var validation in validations)
        {
            await validation();
            if (errors.Count > 0)
            {
                return ValidationResult.Failed(errors);
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM