2011-06-22 70 views
20

使用反射我有一個對象,我需要將其投射到項目的迭代列表中(類型未知,將是對象)。使用Watch窗口,我可以看到我的對象是某種類型的數組,因爲它告訴我元素的數量,我可以分解樹視圖來查看元素本身。C#對象數組

首先,我需要檢查傳遞的對象是某種數組(可能是List,可能是object []等)。然後我需要遍歷該數組。但是,我無法進行類型轉換。

這裏是我如何使用它(略):

private static void Example(object instance, PropertyInfo propInfo) 
    { 
     object anArray = propInfo.GetValue(instance, null); 
     ArrayList myList = anArray as ArrayList; 
     foreach (object element in myList) 
     { 
      // etc 
     } 
    } 

我已經嘗試過各種不同類型轉換。上述不會引發異常,但當anArray實際存在且包含項目時,mylist爲空。正在保存的實際實例是一個強類型列表<>,但如果有必要,可能會佔用有限的表單子集。但是練習的要點是這個Example()方法不知道屬性的基本類型。

+0

你可以找到對象從instance.GetType(類型),你可以使用'is',例如與desirebale類型進行比較'if(instance.GetType()is IEnumerable)' – Tsar

+1

@Bad顯示名稱現在* *關鍵字是如何工作的,你在做什麼試圖從System.Type轉換爲System.Collection.IEnumerable,它不會因爲System.Type沒有實現這個接口,所以不起作用。也許你的意思是** typeof(IEnumerable).IsAssignableFrom(instance.GetType())** – MattDavey

回答

41

它投射到一個ArrayList只會工作,如果對象實際上一個ArrayList。它不適用於System.Array或System.Collections.Generic.List`1例如。

我覺得你其實應該做的是將它轉換爲IEnumerable的,因爲這是你的遍歷它唯一的要求......

object anArray = propInfo.GetValue(instance, null); 
IEnumerable enumerable = anArray as IEnumerable; 
if (enumerable != null) 
{ 
    foreach(object element in enumerable) 
    { 
     // etc... 
    } 
} 
+0

哇,快速的工作和工作!謝謝。 – GeoffM

+1

也感謝其他人。 – GeoffM

14

嘗試投射到IEnumerable。這是所有枚舉,數組,列表等最基本的接口實現。

IEnumerable myList = anArray as IEnumerable; 
if (myList != null) 
{ 
    foreach (object element in myList) 
    { 
     // ... do something 
    } 
} 
else 
{ 
    // it's not an array, list, ... 
} 
1

試試這個:

var myList = anArray as IEnumerable; 
    if (mylist != null) 
    { 
     foreach (var element in myList) 
     { 
      // etc 
     } 
    } 

您也可能需要指定IEnumerable的通用類型,具體取決於您的情況。

1

如果它是任何排序(數組,列表等)的集合,您應該可以將它轉換爲IEnumerable。另外PropertyInfo包含一個PropertyType屬性,您可以使用它來查找實際類型,如果您想要。

1

簡單地嘗試這

string[] arr = ((IEnumerable)yourOjbect).Cast<object>() 
          .Select(x => x.ToString()) 
          .ToArray();