2010-07-07 165 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(); 
     } 
    } 
}