I have to convert a generic object(s) into a NameValueCollection. I am attempting to use reflection. While I can get the parent properties, I cannot get the properties of a 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 assume there has to be somesort of recursive call but cannot figure out how to do it. Any help is appreciated.
I will assume that you want resulting
NameValueCollectionto contain properties from bothClass OneandClass Twowhen the input is of typeClass Two.Now that we have that established, what you can do is to examine a type of each property.
If it’s one of built-in types (
Type.IsPrimitive()can help you determine that), you can add the property to resultingNameValueCollectionright away. Otherwise, you need to go over each property of that non-primitive type and repeat the process for it again. As you mention, here is the place for recursion.