[英]How to reference invalid property in object?
Sorry, If this question seems too broad, but I'm a little unsure how I should do this task. 抱歉,如果这个问题看起来太笼统,但是我不确定我该怎么做。
I have some objects: 我有一些对象:
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;}
}
And a set of validators: 以及一组验证器:
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){...}
}
Error looks like this: 错误看起来像这样:
public class ValidationError
{
public int Code {get;set;}
public string Message {get;set;}
}
I perform validation like this: 我执行这样的验证:
_validator.Validate(new A()).ThrowIfInvalid();
But here is the problem, how to reference invalid property and Serialize/Deserialize this reference to use it on client? 但这是问题所在,如何引用无效的属性并序列化/反序列化此引用以在客户端上使用它?
For example, if new A().c[2].val2
is invalid, I should be able to obtain this path on server and use it on client for my view (obtain PropertyInfo, and object). 例如,如果
new A().c[2].val2
无效,则我应该能够在服务器上获取此路径,并在客户端上将其用于我的视图(获取PropertyInfo和object)。
Is there some extensions/libraries in C# which provide serializable references for properties? C#中是否有一些扩展/库为属性提供可序列化的引用? For example, like XPath in XML.
例如,像XML中的XPath。
Extend class ValidationError
with PropertyPath
property and prepend it on each parent validator 使用
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.