[英]Check for any null values in an object
If I have an object which has other nested objects and properties, like the one below. 如果我有一个具有其他嵌套对象和属性的对象,例如下面的对象和属性。
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 }
}
};
When passing this object to a function I want to check that none of its properties or objects are null
. 当将此对象传递给函数时,我要检查其属性或对象均不为
null
。
public InfoResponse getInfo(request)
{
// Check that the request object has no null properties or objects.
}
Is there a simpler way of checking this than stepping through each child object and property with if statements? 有没有比使用if语句单步检查每个子对象和属性更简单的方法了? A recursive method or something similar?
递归方法还是类似的方法?
Extending 延伸
In my getInfo function I don't want to have to write like this: 在我的getInfo函数中,我不需要这样写:
if (request != null && request.GetInformation != null && ... etc.)
Use reflection and iterate through all the properties to check for null. 使用反射并遍历所有属性以检查是否为空。 Here is a snippet to get started
这是一个入门片段
using System.Reflection;
GetInfoRequest objGetInfoRequest;
Type getInfoRequestType = objGetInfoRequest.GetType();
PropertyInfo[] myProps = getInfoRequestType.GetProperties();
you could use reflection to iterate through the fields. 您可以使用反射来遍历字段。
you well need some recursion for the nested values. 您非常需要对嵌套值进行一些递归。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.