2012-03-28 205 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。否则,您需要查看该非原始类型的每个属性,然后重复该过程。如你所说,这里是递归的地方。