当前位置:编程学习 > C#/ASP.NET >>

反射 动态实例化 如何实例化嵌套类成员?

 public TestA()
        {
            Console.WriteLine("构造TestA");
        }
        private string id;
        private string name;
        
         public string Id
        {
            get { return id; }
            set { id = value; }
        }
       
        public string Name
        {
            get { return name; }
            set { id = value; }
        }
    }

   public  class TestB
    {
         public TestB()
        {
            Console.WriteLine("构造TestB"); 
        }
         private TestA b ;

         public TestA B
         {
             get { return b; }
             set { b = value; }
         }    
需要先动态实例化TestB,然后再实例化TestB中的TestA类对象,第一步可以实现,第二步不知道怎么办。。
--------------------编程问答--------------------
TestB b = new TestB();
b.B = new TestA();
--------------------编程问答--------------------
Type tb = typeof(TestB);
ConstructorInfo tbci = tb.GetConstructor(Type.EmptyTypes);
object testb = tbci.Invoke(new object[0]);

Type ta = typeof(TestA);
ConstructorInfo taci = ta.GetConstructor(Type.EmptyTypes);
object testa = taci.Invoke(new object[0]);

FieldInfo tbfi = tb.GetField("b", BindingFlags.NonPublic| BindingFlags.Instance);
tbfi.SetValue(testb, testa);
--------------------编程问答-------------------- 想知道答案······
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,