2012-06-25 34 views
0

我需要從對象中的所有數據轉儲到兩dimetional陣列獲取來自對象中的所有數據到一個二維數組

這就是聲明:

GetItemCall oGetItemCall = new GetItemCall(oContext); 

然後,我可以使用oGetItemCall.Item.ConditionIDoGetItemCall.Item.ListingDetails.EndTime

oGetItemCall對象有很多變量,我想將它們添加到一個易於閱讀的2維數組。 有沒有辦法做到這一點?

回答

0

數組是必需的嗎? 爲什麼不使用更靈活的結構,如列表。所以嘗試將對象轉換爲列表。 A list可以通過索引輕鬆訪問:在這種情況下通過對象的屬性名稱。 Reflection可以解決問題。 看一看here

0

目前尚不清楚爲什麼你會這麼做,但是其中任何一個都應該這樣做。

 string[,] some = new string[100,2]; 
     Hashtable table = new Hashtable(); 

     // array 
     some[0,0] = "Key"; 
     some[0,1] = "value"; 

     // hashtable 
     table["key"] = "value"; 
0

所以你想看看該項目及其所有屬性和值?使用反射。

這不是完美的,絕不是完整的 - 但會給你一個很好的起點,如果這是你想要的。輕鬆擴展到補充型名稱等

public static List<string> ReflectObject(object o) 
{ 
    var items = new List<string>(); 

    if (o == null) 
    { 
     items.Add("NULL"); // remove if you're not interested in NULLs. 
     return items; 
    } 

    Type type = o.GetType(); 

    if (type.IsPrimitive || o is string) 
    { 
     items.Add(o.ToString()); 
     return items; 
    } 

    items.Add(string.Format("{0}{1}{0}", " ----- ", type.Name)); 

    if (o is IEnumerable) 
    { 
     IEnumerable collection = (IEnumerable)o; 
     var enumerator = collection.GetEnumerator(); 

     while (enumerator.MoveNext()) 
     { 
      foreach (var innerItem in ReflectObject(enumerator.Current)) 
      { 
       items.Add(innerItem); 
      } 
     } 
    } 
    else 
    { 
     var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); 

     foreach (var property in properties) 
     { 
      object value = property.GetValue(o, null); 

      foreach (var innerItem in ReflectObject(value)) 
      { 
       items.Add(string.Format("{0}: {1}", property.Name, innerItem)); 
      } 
     } 
    } 

    return items; 
} 

它可以像這樣使用:

Test t = new Test(); 
t.MyProperty1 = 123; 
t.MyProperty2 = "hello"; 
t.MyProperty3 = new List<string>() { "one", "two" }; 
t.MyTestProperty = new Test(); 
t.MyTestProperty.MyProperty1 = 987; 
t.MyTestProperty.MyTestProperty = new Test(); 
t.MyTestProperty.MyTestProperty.MyProperty2 = "goodbye"; 

var items = MyReflector.ReflectObject(t); 

foreach (var item in items) 
{ 
    Console.WriteLine(item); 
} 

這將導致:

----- Test ----- 
MyProperty1: 123 
MyProperty2: hello 
MyProperty3: ----- List`1 ----- 
MyProperty3: one 
MyProperty3: two 
MyTestProperty: ----- Test ----- 
MyTestProperty: MyProperty1: 987 
MyTestProperty: MyProperty2: NULL 
MyTestProperty: MyProperty3: NULL 
MyTestProperty: MyTestProperty: ----- Test ----- 
MyTestProperty: MyTestProperty: MyProperty1: 0 
MyTestProperty: MyTestProperty: MyProperty2: goodbye 
MyTestProperty: MyTestProperty: MyProperty3: NULL 
MyTestProperty: MyTestProperty: MyTestProperty: NULL