我必须将泛型对象转换为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;
}我假设一定有某种递归调用,但是我不知道该怎么做。任何帮助都是非常感谢的。
发布于 2012-03-29 05:07:07
我假设当输入是Class Two类型时,您希望生成的NameValueCollection包含来自Class One和Class Two的属性。
现在我们已经确定了这一点,您可以做的是检查每个属性的一种类型。如果是内置类型(Type.IsPrimitive()可以帮助您确定),则可以立即将该属性添加到生成的NameValueCollection中。否则,您需要遍历该非基元类型的每个属性,并再次重复该过程。正如您所提到的,这里是递归的地方。
https://stackoverflow.com/questions/9914944
复制相似问题