簡體   English   中英

如何引用對象中的無效屬性?

[英]How to reference invalid property in object?

抱歉,如果這個問題看起來太籠統,但是我不確定我該怎么做。

我有一些對象:

public class A
{
    public B b {get;set;}
    public C[] cList {get;set;}
}

public class B
{
    public string val1 {get;set;}
}

public class C
{
    public string val2 {get;set;}
}

以及一組驗證器:

public class AValidator : IValidator<A>
{
    IEnumerable<ValidationError> Validate(A obj){...}
}

public class BValidator : IValidator<B>
{
    IEnumerable<ValidationError> Validate(B obj){...}
}

public class CValidator : IValidator<C>
{
    IEnumerable<ValidationError> Validate(C obj){...}
}

錯誤看起來像這樣:

public class ValidationError
{
    public int Code {get;set;}
    public string Message {get;set;}
}

我執行這樣的驗證:

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

但這是問題所在,如何引用無效的屬性並序列化/反序列化此引用以在客戶端上使用它?

例如,如果new A().c[2].val2無效,則我應該能夠在服務器上獲取此路徑,並在客戶端上將其用於我的視圖(獲取PropertyInfo和object)。

C#中是否有一些擴展/庫為屬性提供可序列化的引用? 例如,像XML中的XPath。

使用PropertyPath屬性擴展類ValidationError並將其放在每個父驗證器上

public class AValidator : IValidator<A>
{
    IEnumerable<ValidationError> Validate(A obj)
    {
        if(obj.b == null)
            yield return new ValidationError {Message = "b is null", PropertyPath = "a.b"};
        else
        { 
            var bresults = new BValidator().Validate(obj.b);
            foreach(var result in bresults)
            {
                result.PropertyPath = "a.b." + result.PropertyPath;
                yield return result;
            }
        }
...
            var cresults = new BValidator().Validate(obj.c[i]);
            foreach(var result in cresults)
            {
                result.PropertyPath = "a.c[i]." + result.PropertyPath;
                yield return result;
            }
    }        
}

暫無
暫無

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

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