2010-07-07 168 views
11
FieldInfo[] fields = typeof(MyDictionary).GetFields(); 

MyDictionary是一個靜態類,所有字段都是字符串數組。C#反射:如何獲取數組值和長度?

如何獲得每個數組的長度值,然後遍歷所有元素? 我試着投這樣的:

field as Array 

但它會導致一個錯誤

無法通過引用轉換轉換型「System.Reflection.FieldInfo」到「的System.Array」 ,裝箱轉換,拆箱轉換, 包裝轉換或null類型轉換

+0

究竟你想做 ? – 2010-07-07 11:37:14

+0

我需要遍歷所有數組的元素來檢查是否存在任何數組中的某些值 – Tony 2010-07-07 11:39:11

回答

9

編輯您的編輯後:請注意,你有我而不是與你自己的類相關的對象或值。換句話說,那些FieldInfo對象在你的類的所有實例中是共同的。獲取字符串數組的唯一方法是使用這些FieldInfo對象來獲取您的類的特定實例的字段值。

爲此,您使用FieldInfo.GetValue。它將該字段的值作爲對象返回。

既然你已經知道他們是字符串數組,它簡化了的東西:

如果字段是靜態的,通過null下面的obj參數。

foreach (var fi in fields) 
{ 
    string[] arr = (string[])fi.GetValue(obj); 
    ... process array as normal here 
} 

如果你想確保你只處理領域與字符串數組:

foreach (var fi in fields) 
{ 
    if (fi.FieldType == typeof(string[])) 
    { 
     string[] arr = (string[])fi.GetValue(obj); 
     ... process array as normal here 
    } 
} 
+0

好的,但在這種情況下,我按'obj'將是MyDictionary類的一個實例,但我不能創建一個實例因爲它是一個靜態類 – Tony 2010-07-07 11:42:31

+0

只需傳遞null作爲obj,我沒有完全讀完你的問題:) – 2010-07-07 11:48:50

+0

@Tony只是傳遞null而不是obj – 2010-07-07 11:51:17

4

像這樣:

FieldInfo[] fields = typeof(MyDictionary).GetFields(); 
foreach (FieldInfo info in fields) { 
    string[] item = (string[])info.GetValue(null); 
    Console.WriteLine("Array contains {0} items:", item.Length); 
    foreach (string s in item) { 
    Console.WriteLine(" " + s); 
    } 
} 
8

舉個例子:

using System; 
using System.Reflection; 

namespace ConsoleApplication1 
{ 
    public static class MyDictionary 
    { 
     public static int[] intArray = new int[] { 0, 1, 2 }; 
     public static string[] stringArray = new string[] { "zero", "one", "two" }; 
    } 

    static class Program 
    { 
     static void Main(string[] args) 
     { 
      FieldInfo[] fields = typeof(MyDictionary).GetFields(); 

      foreach (FieldInfo field in fields) 
      { 
       if (field.FieldType.IsArray) 
       { 
        Array array = field.GetValue(null) as Array; 

        Console.WriteLine("Type: " + array.GetType().GetElementType().ToString()); 
        Console.WriteLine("Length: " + array.Length.ToString()); 
        Console.WriteLine("Values"); 
        Console.WriteLine("------"); 

        foreach (var element in array) 
         Console.WriteLine(element.ToString()); 
       } 

       Console.WriteLine(); 
      } 

      Console.Readline(); 
     } 
    } 
}