我有一个push类属性的方法到NameValuCollection
private NameValueCollection ObjectToCollection(object objects)
{
NameValueCollection parameter = new NameValueCollection();
Type type = objects.GetType();
PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance |
BindingFlags.DeclaredOnly |
BindingFlags.Public);
foreach (PropertyInfo property in properties)
{
if (property.GetValue(objects, null) == null)
{
parameter.Add(property.Name.ToString(), "");
}
else
{
if (property.GetValue(objects, null).ToString() != "removeProp")
{
parameter.Add(property.Name.ToString(), property.GetValue(objects, null).ToString());
}
}
}
return parameter;
}
在我的情况下,当我将My Model类传递给此方法时,它是正确的,但是在我的Model类中,我使用另一个这样的模型
public class Brand
{
public MetaTags MetaTag { get; set; } // <---- Problem is here
public string BrandName { get; set; }
}
public class MetaTags
{
public string Title { get; set; }
public string Description { get; set; }
public string Language { get; set; }
}
它不会将MetaTags类属性添加到集合中,只需将MetaTag添加到集合
我希望此方法返回此OutPut
key:Title Value:value
key:Description Value:value
key:Language Value:value
key:BrandName Value:value
但是此方法会返回此
key:MetaTag Value:
key:BrandName Value:value
我怎么能这样做? 非常感谢你的帮助
答案 0 :(得分:0)
在添加空字符串之前,请检查当前属性是否为MetaTags
。如果是这样,请递归使用此函数。
private NameValueCollection ObjectToCollection(object objects)
{
NameValueCollection parameter = new NameValueCollection();
Type type = objects.GetType();
PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance |
BindingFlags.DeclaredOnly |
BindingFlags.Public);
foreach (PropertyInfo property in properties)
{
if (property.PropertyType == typeof(MetaTags))
{
parameter.Add(property.Name.ToString(),ObjectToCollection(property.GetValue(objects, null)))
}
else{
if (property.GetValue(objects, null) == null)
{
parameter.Add(property.Name.ToString(), "");
}
else
{
if (property.GetValue(objects, null).ToString() != "removeProp")
{
parameter.Add(property.Name.ToString(), property.GetValue(objects, null).ToString());
}
}
}
}
return parameter;
}