2012-03-28 202 views
3

我必須將一個或多個通用對象轉換爲NameValueCollection。我正在嘗試使用反射。儘管我可以獲取父屬性,但我無法獲取作爲對象的父屬性的屬性。將對象轉換爲NameValueCollection

Class One 
public string name{get;set} 

Class Two 
public string desc{get;set} 
public One OneName{get;set;} 

public static NameValueCollection GetPropertyName(
     string objType, object objectItem) 
{ 
    Type type = Type.GetType(objType); 
    PropertyInfo[] propertyInfos = type.GetProperties(); 
    NameValueCollection propNames = new NameValueCollection(); 

    foreach (PropertyInfo propertyInfo in objectItem.GetType().GetProperties()) 
    { 
     if (propertyInfo.CanRead) 
     { 
      var pName = propertyInfo.Name; 
      var pValue = propertyInfo.GetValue(objectItem, null); 
      if (pValue != null) 
      { 
       propNames.Add(pName, pValue.ToString()); 
      } 
     } 
    } 

    return propNames; 
} 

我認爲必須有一些遞歸調用,但不知道如何去做。任何幫助表示讚賞。

+1

'objType'是'objectItem'的類型嗎?如果是這樣,你可以刪除該參數。你還創建了一個你不使用的'propertyInfos'變量。 – ThatMatthew 2012-03-28 20:23:57

+0

我現在可以正確使用此代碼 – 2012-05-19 11:30:23

回答

0

我會假設您希望生成的NameValueCollection包含來自Class OneClass Two的輸入類型爲Class Two的屬性。

現在我們已經確定了,你可以做的是檢查每個屬性的類型。 如果是內置類型之一(Type.IsPrimitive()可以幫助您確定),則可以立即將該屬性添加到生成的NameValueCollection。否則,您需要查看該非原始類型的每個屬性,然後重複該過程。如你所說,這裏是遞歸的地方。