I want to get all properties of an object during runtime and save it on a batabase together with its values. I am doing this recursively i.e. whenever a property is also on object, I will call the same method and pass the property as a parameter.
See my code below:
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));
}
}
}
}
However, The problem with my current code is I create a new instance for property objects (see emphasis) thus losing all data that was on the original object. How can I recursively iterate on all the properties of an object? Is this possible?
Please help. Thanks in advance.
Use this instead to replace your emphasized line:
SaveProperties (propertyInfo.GetValue (entity, null));
I would also do something like this to make sure GetValue()
is applicable and to avoid multiple calls to it:
object v = propertyInfo.CanRead ? propertyInfo.GetValue (entity, null) : null;
if (v != null) {
if (...) {
} else {
SaveProperties (v);
}
}
精彩评论