从ViewModel获取属性

我有一个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 

我怎么能这样做? 非常感谢你的帮助

在添加空字符串之前,请检查当前属性是否为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; }