2012-02-11 99 views
0

我已经构建了 “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; 
     } 
+4

请发布一小组可用于重现问题的代码。 – 2012-02-11 19:22:54

回答

2

似乎您试图从你的通用属性的类型代表的类型得到属性值。这是不可能的,因为你必须有一个实例来获取值。没有与Type参数关联的实例,所以没有属性值可以获取。

也许如果你可以提供更多的背景来尝试实现,我们可以帮助你达到目标。

+0

好吧,是的。在第一次迭代时,实例将会是对象,但是在第二次迭代中,将会推送什么?因为对象是通用的? – Elena 2012-02-11 20:17:44

+0

@Elena - 我重写了我的答案以提供一些见解。为了帮助您解决问题,我们需要更好地了解您要实现的目标。 – 2012-02-11 21:42:31