Convert Object to NameValueCollection

I need to convert a generic object to a NameValueCollection. I am trying to use reflection. Although I can get the parent properties, I cannot get the properties of the parent property that is an object.

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

      

I'm guessing there should be somesort recursive call, but can't figure out how to do it. Any help is appreciated.

+3


source to share


1 answer


I assume you want the result to NameValueCollection

contain properties both from Class One

and Class Two

when the input is of type Class Two

.



Now that we've set this up, you can check the type of each property. If one of the built-in types ( Type.IsPrimitive()

can help you figure it out), you can add the property to the final right away.Otherwise NameValueCollection

, you have to go through each property of that non-primitive type and repeat the process for it again. As you mentioned, here's the place for recursion.

0


source







All Articles