将Object转换为NameValueCollection

时间:2012-03-28 20:12:39

标签: c# reflection

我必须将通用对象转换为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 个答案:

答案 0 :(得分:0)

当输入的类型为NameValueCollection时,我假设您希望结果Class One包含来自Class TwoClass Two的属性。

现在我们已经建立了,你可以做的是检查每个属性的类型。 如果它是内置类型之一(Type.IsPrimitive()可以帮助您确定),则可以立即将属性添加到生成的NameValueCollection。否则,您需要遍历该非基本类型的每个属性,并再次重复该过程。如你所述,这里是递归的地方。