C#反思:如何让一个数组值和放大器;长度? [英] C# Reflection : how to get an array values & length?

查看:84
本文介绍了C#反思:如何让一个数组值和放大器;长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 的FieldInfo []栏= typeof运算(MyDictionary).GetFields(); 



MyDictionary 是一个静态类,各领域是字符串数组。



如何再itearate通过所有元素得到获取每个数组的长度值?
我试着投这样的:

 字段作为数组

但它会导致一个错误




无法将类型'的System.Reflection .FieldInfo'到'通过引用转换,装箱转换,取消装箱转换,
包装转换或null类型转换


$ b $的System.Array'
b
解决方案

修改后您的修改:请注意,你所拥有的是反思的对象,没有涉及到自己的类对象或值。换句话说,那些字段信息对象必须有共同的类的所有实例。才能到字符串数组的唯一方法是使用那些字段信息对象到你类的特定实例的字段值。



有关这一点,你使用 FieldInfo.GetValue 。它返回领域为对象的值



既然你已经知道他们是字符串数组,它简化了的东西:



如果该字段是静态的,通过下面的 OBJ 参数。

 的foreach(在领域VAR FI)
{
的String [] = ARR(字符串[])fi.GetValue(OBJ) ;
...处理阵列正常这里
}

如果你想确保你只用字符串数组处理领域:

 的foreach(在领域VAR FI)
{
如果(fi.FieldType == typeof运算(字符串[]))
{
的String [] = ARR(字符串[])fi.GetValue(OBJ);
...处理阵列正常这里
}
}


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, wrapping conversion, or null type conversion

解决方案

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
    }
}

这篇关于C#反思:如何让一个数组值和放大器;长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆