检查class的任何属性是否为null [英] Check if any property of class is null

查看:133
本文介绍了检查class的任何属性是否为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:-

  public class要求
{
public string EventMessageUId {get ;组; }
公用字串ProjectId {get;组; }
public List< Message>讯息{get;组; }
}

我使用传入的Json映射它:-

  Requirements objRequirement = JsonObject.ToObject< Requirements>(); 

我想检查上述映射后class的任何属性是否没有值或为空。



为此我尝试了:-

  bool isNull = objRequirement.GetType( ).GetProperties()。All(p => p!= null); 

但是在调试时,我发现属性是否在每次赋值为true时都为Null。 p>

请帮助我如何通过<$ / $ foreach 循环来实现这一目标。

解决方案

您正在检查属性自身是否为null(永远不会为真),而不是属性的值。改用它:

  bool isNull = objRequirement.GetType()。GetProperties()
.All(p => ; p.GetValue(objRequirement)!= null);


I have following class:-

public class Requirements
    {
        public string EventMessageUId { get; set; }
        public string ProjectId { get; set; }        
        public List<Message> Message { get; set; }        
    }

I am mapping it with incomming Json:-

Requirements objRequirement = JsonObject.ToObject<Requirements>();

I wanted to check if any property of class has no value or left null after above mapping.

For this I tried :-

bool isNull= objRequirement.GetType().GetProperties().All(p => p != null);

But while debugging I found that whether property left Null or not each time it gives value true.

Please help me how can I achieve this by Avoioding For/foreach loop.

解决方案

You're checking if the properties themselves are null (which will never be true), not the values of the properties. Use this instead:

bool isNull = objRequirement.GetType().GetProperties()
                            .All(p => p.GetValue(objRequirement) != null);

这篇关于检查class的任何属性是否为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆