2015-09-21 41 views
0

我将XML反序列化为类模型,我想检查是否有任何未正确反序列化的XML节点。检查任何属性为空

我的类看起来是这样的:

class A 
{ 
    public A1 pop1; 
    public A2 prop2; 

    // like so n number of classes 
} 
class A1 
{ 
    public string Item1{get;set;} 
    public string Item2{get;set;} 
    public string Item3{get;set;} 

    // like so n number of classes 
} 

class A2 
{ 
    public string Item1{get;set;} 
    public string Item2{get;set;} 
    public string Item3{get;set;} 

    // like so n number of classes 
} 

有没有一种方法来检查,如果任何对象A1A2的等是null任何对象内部的属性为null或空?如果这是真的,那么反序列化失败。

回答

4

您可以使用反射遍历类和它们的值。

我在这种情况下做的是在接口IValidateable中制作一个名为Validate的自定义方法。让每个类都实现该接口并编写一个方法来进行验证。这使得偏离现在的“所有属性不能为空”规则变得更容易。

+0

您能否建议一个示例代码来开始它? –

+0

像这样的东西? https://dotnetfiddle.net/UPGe58 @JibinMathew –

1

你可以使用something like this

public bool HasAllEmptyProperties() 
{ 
    var type = GetType(); 
    var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); 
    var hasProperty = properties.Select(x => x.GetValue(this, null)) 
           .Any(y => y != null && !String.IsNullOrWhiteSpace(y.ToString())); 
    return !hasProperty; 
} 

我也已经使用了所有的()方法和积极的比较,而不是任何()。但是这样做效率不高,因为所有元素都必须根据条件进行检查,而只要元素满足条件,Any()就会返回