[英]Check for any null values in an object
如果我有一个具有其他嵌套对象和属性的对象,例如下面的对象和属性。
var request = new GetInfoRequest
{
GetInformation = new GetInformationType
{
Code = "abc",
Id = "123",
Item = new InfoItem
{
Itemid = "test",
ItemName = "testname"
},
StartDate = new StartdatumType { Start = new DateTime(1990, 1, 1)},
EndDate = new EndDateType { End = new DateTime.Now }
}
};
当将此对象传递给函数时,我要检查其属性或对象均不为null
。
public InfoResponse getInfo(request)
{
// Check that the request object has no null properties or objects.
}
有没有比使用if语句单步检查每个子对象和属性更简单的方法了? 递归方法还是类似的方法?
延伸
在我的getInfo函数中,我不需要这样写:
if (request != null && request.GetInformation != null && ... etc.)
使用反射并遍历所有属性以检查是否为空。 这是一个入门片段
using System.Reflection;
GetInfoRequest objGetInfoRequest;
Type getInfoRequestType = objGetInfoRequest.GetType();
PropertyInfo[] myProps = getInfoRequestType.GetProperties();
您可以使用反射来遍历字段。
您非常需要对嵌套值进行一些递归。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.