C# Reflection : how to get an array values & length?

后端 未结 3 703
北荒
北荒 2020-12-17 16:24
FieldInfo[] fields = typeof(MyDictionary).GetFields();

MyDictionary is a static class, all fields are string arrays.

How to ge

相关标签:
3条回答
  • 2020-12-17 17:06

    Like this:

    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);
      }
    }
    
    0 讨论(0)
  • 2020-12-17 17:23

    As an example:

    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();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-17 17:27

    Edit after your edit: Note that what you have is reflection objects, not objects or values related to your own class. In other words, those FieldInfo objects you have there are common to all instances of your class. The only way to get to the string arrays is to use those FieldInfo objects to get to the field value of a particular instance of your class.

    For that, you use FieldInfo.GetValue. It returns the value of the field as an object.

    Since you already know they are string arrays, that simplifies things:

    If the fields are static, pass null for the obj parameter below.

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

    If you want to ensure you only process fields with string arrays:

    foreach (var fi in fields)
    {
        if (fi.FieldType == typeof(string[]))
        {
            string[] arr = (string[])fi.GetValue(obj);
            ... process array as normal here
        }
    }
    
    0 讨论(0)
提交回复
热议问题