C# Reflection : how to get an array values & length?
FieldInfo[] fields = typeof(MyDictionary).GetFields();
MyDictionary
is a static class, all fields are string arrays.
How to get get the Length value of each array and then itearate through all elements ? I tried the cast like:
field as Array
but it causes an error
Cannot convert type 'System.Reflection.FieldInfo' to 'System.Array' via a reference conversion, boxing conversion, unboxing conversion, wrapp开发者_如何学运维ing conversion, or null type conversion
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();
}
}
}
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
}
}
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);
}
}
精彩评论