我希望在运行时获取对象的所有属性,并将其与其值一起保存在数据库中.我正在递归地执行此操作,即每当属性也在对象上时,我将调用相同的方法并将该属性作为参数传递.
请参阅下面的代码:
private void SaveProperties(object entity) {
PropertyInfo[] propertyInfos = GetAllProperties(entity);
Array.Sort(propertyInfos,
delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
{ return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });
_CurrentType = entity.GetType().Name;
foreach (PropertyInfo propertyInfo in propertyInfos) {
if (propertyInfo.GetValue(entity, null) != null) {
if (propertyInfo.PropertyType.BaseType != typeof(BaseEntity)) {
SaveProperty((BaseEntity)entity, propertyInfo);
}
else {
// **here**
SaveProperties(Activator.CreateInstance(propertyInfo.PropertyType));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我当前代码的问题是我为属性对象创建了一个新实例(请参阅强调),从而丢失了原始对象上的所有数据.如何递归迭代对象的所有属性?这可能吗?
请帮忙.提前致谢.
使用它代替你强调的行:
SaveProperties (propertyInfo.GetValue (entity, null));
Run Code Online (Sandbox Code Playgroud)
我也会这样做以确保GetValue()适用并避免多次调用它:
object v = propertyInfo.CanRead ? propertyInfo.GetValue (entity, null) : null;
if (v != null) {
if (...) {
} else {
SaveProperties (v);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2058 次 |
| 最近记录: |