using System.Reflection;
PropertyInfo[] propertys = data.GetType().GetProperties();
foreach (PropertyInfo property in propertys)
{
if (property.GetValue(data, null) == null)
{
property.SetValue(data, property.Name, null);
}
}
本文介绍了一种使用C#中的System.Reflection命名空间来遍历对象的所有属性并为那些值为null的属性设置新值的方法。这种方法可以应用于初始化对象或者进行数据验证等场景。
using System.Reflection;
PropertyInfo[] propertys = data.GetType().GetProperties();
foreach (PropertyInfo property in propertys)
{
if (property.GetValue(data, null) == null)
{
property.SetValue(data, property.Name, null);
}
}
4919
1750

被折叠的 条评论
为什么被折叠?