您的位置:首页 > 其它

.NET 判断对象所有属性是否为空

2017-09-10 01:46 393 查看
如题,此实例考虑对象属性较多的情况(暂不考虑此对象设计是否合理),当想要验证众多对象是否为空时,If Else不在考虑之列,期望用最简单的代码实现,如下:

参考:https://codereview.stackexchange.com/questions/70341/check-if-any-of-class-properties-is-not-null-empty-was-assigned

代码:

ObjectProperties op = new ObjectProperties();
op.name = "test";
op.age = 15;

StringBuilder sb = new StringBuilder();

PropertyInfo[] properties = op.GetType().GetProperties();
foreach (PropertyInfo pi in properties)
{
if (pi.GetValue(op,null) != ""  && pi.GetValue(op, null) != null)
{
sb.Append(
string.Format("Name: {0} | Value: {1}",
pi.Name,
pi.GetValue(op, null)
)
);
}

}
Console.WriteLine(sb.ToString());
Console.ReadLine();

}


代码逻辑简单,控制台应用程序实现,关键代码 pi.GetValue(op, null) ,已运行通过,达到期望,如有错,请指正。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: