假设一段代码:
  struct test
{
    a1;
    a2;
    a3;
}
  string b = "a1";
  我现在想要用b来输出变量a1的值,这个有什么方法吗?
  即:test t;
     t.a1=10;
    我cout<<b;输出的是a1,但我想输出a1的值。
  structstring

解决方案 »

  1.   

    用反射
    http://blog.csdn.net/pengchengwanli/article/details/5418554
      

  2.   

    用反射可以实现
     public static void Main()
        {
            test t = new test();
            t.a1 = 10;
            string b = "a1";        Type T=t.GetType();
            System.Reflection.FieldInfo fi = T.GetField(b);
            if (fi != null)
            {
                int value = (int)fi.GetValue(t);
                Console.WriteLine("{0}={1}", b, value);
            }
        }    struct test
        {
            public int a1;
            public int a2;
            public int a3;
        }