日期:2014-05-18  浏览次数:20878 次

求救!怎样通过反射获取数组的值?
C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Testa testa = new Testa();
            testa.Name = "Eric";
            testa.Value = "good";
            Testb testb1 = new Testb();
            testb1.Address = "上海";
            testb1.Company = "微软";
            Testb testb2 = new Testb();
            testb1.Address = "北京";
            testb1.Company = "IBM";
            Testb[] testbArry = { testb1, testb2 };
            testa.testbs = testbArry;

            FieldInfo[] fieldInfoes = testa.GetType().GetFields();
            foreach (FieldInfo fieldInfo in fieldInfoes)
            {
                if (fieldInfo.FieldType == typeof(string))
                {
                    Console.WriteLine(string.Format("{0},{1}", fieldInfo.GetValue(testa), fieldInfo.FieldType));
                }
                if (fieldInfo.FieldType == typeof(Testb[]))
                {
                    //这里怎么写啊?取不出值,晕死了,搞了一晚上也没搞出来,好心人帮个忙吧。

                }
            }
            Console.ReadLine();
        }
    }
    public class Testa
    {
        public string Name;

        public string Value;

        public Testb[] testbs;

    }

    public class Testb
    {
        public string Company;

        public string Address;
    }

}




------解决方案--------------------
那个类型是没有拿准。好像是重assembly里拿到那个真实的类型名字的。
------解决方案--------------------
???你不是已经判断出Testb[]类型了吗?

Testb[] list = (Testb[])fieldInfo.GetValue(testa);
foreach (var testb in list)
{
Console.WriteLine(testb.Company+" "+testb.Address);
}

另外,你上面有个地方不知是不是写错了:
Testb testb2 = new Testb();
testb1.Address = "北京";
testb1.Company = "IBM";
Testb[] testbArry = { testb1, testb2 };