首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

!怎样通过反射获取数组的值

2012-03-24 
求救!怎样通过反射获取数组的值?C# codeusing Systemusing System.Collections.Genericusing System.Lin

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

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

热点排行