3
我必须将一个或多个通用对象转换为NameValueCollection。我正在尝试使用反射。尽管我可以获取父属性,但我无法获取作为对象的父属性的属性。将对象转换为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;
}
我认为必须有一些递归调用,但不知道如何去做。任何帮助表示赞赏。
'objType'是'objectItem'的类型吗?如果是这样,你可以删除该参数。你还创建了一个你不使用的'propertyInfos'变量。 – ThatMatthew 2012-03-28 20:23:57
我现在可以正确使用此代码 – 2012-05-19 11:30:23