2010-10-25 104 views
3

我想在運行時獲取對象的所有屬性,並將它與其值一起保存在batabase上。我這樣做是遞歸的,即每當一個屬性也在對象上時,我將調用相同的方法並將該屬性作爲參數傳遞。遞歸迭代地處理對象的屬性

見下面我的代碼:

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)); 
      } 
     } 
    } 
} 

不過,我目前的代碼的問題是我創建的屬性對象(見強調)從而失去了,這是原來的對象上的所有數據的新實例。我如何遞歸迭代對象的所有屬性?這可能嗎?

請幫忙。提前致謝。

+0

我會編輯刪除重點並在該行上方放置一個「//註釋」。 – IAbstract 2010-10-25 02:53:09

回答

5

使用此,而不是取代您強調線:

SaveProperties (propertyInfo.GetValue (entity, null)); 

我還要做這樣的事情,以確保GetValue()適用,避免多次調用它:

object v = propertyInfo.CanRead ? propertyInfo.GetValue (entity, null) : null; 
if (v != null) { 
    if (...) { 
    } else { 
     SaveProperties (v); 
    } 
} 
+0

它的工作!謝啦!我知道我只是錯過了一些東西。必須來自太多的咖啡和睡眠時間太少。 – third 2010-10-25 03:09:43

+0

@third:借調 – 2012-01-19 07:26:53