簡體   English   中英

如何根據屬性的運行時類型動態選擇驗證器?

[英]How to dynamically select a validator based on property's runtime type?

給定一個具有通用參數的基類,該通用參數用於定義屬性的類型並且對另一種基類型有限制,在為派生類編寫Fluent驗證器時,該驗證器如何切換將哪個子驗證器應用於對象?通用財產?

以下是一些示例類來演示此配置:

public abstract class BaseParent<TChildType> where TChildType : BaseChild
{
    public TChildType Child {get; set;}
}

public abtract class BaseChild
{
    public sting ChildPropOne {get; set;}
}

public class ChildA : BaseChild
{
    public string ChildAPropOne {get; set;}
}

public class ChildB: BaseChild
{
    public string ChildBPropOne {get; set;}
}

public class ParentA<TChildType> : BaseParent<TChildType> where TChildType : BaseChild
{
    public string ParentAPropOne {get; set;}
}

public class ParentB<TChildType> : BaseParent<TChildType> where TChildType : BaseChild
{
    public string ParentBPropOne {get; set;}
}

我當前的設置為每個父類型+子類型組合強制使用不同的驗證器類。 理想情況下,我可以為每個父母編寫一個驗證者,為每個孩子編寫一個驗證者,並讓該父驗證者能夠選擇要調用的子驗證者

您可以將孩子的驗證器實例注入到父驗證器中,並使用SetValidator for Child屬性:

public class ParentAValidator<TChildType> : AbstractValidator<ParentA<TChildType>> where TChildType : BaseChild
{
    public ParentAValidator(IValidator<TChildType> childValidator)
    {
        RuleFor(p => p.Child).SetValidator(childValidator);
    }
}

暫無
暫無

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

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