2012-02-11 125 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