我已经构建了 “deserialiazes” 以下列方式的对象的一般方法:C#的PropertyInfo的GetValue
public class AClass
{
public int Id {get; set;}
public string Name {get;set;}
}
public class NestingClass
{
public string Address {get; set;}
List<AClass> Classes {get; set;}
}
输出,如果keyvaluepair的列表:NestingClass值:无,AddressNestingClass值, List1.Generic .Collections ClassesNestingClass none,IdAClassNestingClass的值,NameAClassNestingClass的值。我使用propertyInfo.GetValue()我不能总是使用对象,例如对于一个AClass的propertyInfos对象(这是类型的类型)它构成了类的列表),该对象应该是AClass类型的。使用“这个”也不起作用。我得到的对象与目标对象不匹配。 我需要的是通过作为泛型参数传递的对象“切片”的某种机制,并尝试以这种方式获取值。 的代码是一样的东西:
public List<KeyValuePair<string,string>> Process(object foo)
{
if (foo == null)
return new List<KeyValuePair<string,string>>();
var result = List<KeyValuePair<string,string>>();
var types = new Stack<Helper>();
types.Push(new Helper { Type = o.GetType(),Name = string.Empty, Value = string.Empty });
while (types.Count > 0)
{
Helper tHelper = types.Pop();
Type t = tHelper.Type;
result.Items.Add(new KeyValuePair { Key = tHelper.Name, Value = tHelper.Value });
if (t.IsValueType || t == typeof(string))
continue;
if (t.IsGenericType)
{
foreach (var arg in t.GetGenericArguments())
types.Push(new TypeHelper { Type = arg, Name = string.Empty });
continue;
}
foreach (var propertyInfo in t.GetProperties())
{
//here comes the issue
types.Push(new TypeHelper { Type = propertyInfo.PropertyType, Name = propertyInfo.Name + propertyInfo.DeclaringType.Name, Value= propertyInfo.GetValue(this,null).ToString() });
}
}
return result;
}
请发布一小组可用于重现问题的代码。 – 2012-02-11 19:22:54