class Bill  //单据类
{
public Users  objUser=new Users ();  //建单人对象
public string BillName=string.Empty ; //单据名称
public DateTime CreateDate=System.DateTime .Now ; //建单日期
   
public Bill(string _BillName )
{
this.BillName =_BillName;
}
} class Users  //员工
{
public string UserId=string.Empty ;
public string USerName=string.Empty ; public Users()
{
this.UserId ="001";
this.USerName ="张三";
}
} class Test
{
public Bill objBill=new Bill ("testBill");  //单据对象 
protected DataTable DT;  //想要建立的表  public Test()
{} /// <summary>
/// 建立一个表,表有四列 为:单据名称,建单日期,建单人编号,建单人姓名,并将objBill中的数据作为一行填入表中
/// </summary>
private void InitData() 
{
Type objType=this.objBill .GetType();
System.Reflection.PropertyInfo[] mi =objType.GetProperties ();
foreach(System.Reflection.PropertyInfo m in objType)
{
//对象的每一个属性作为主表的一列
DTPrintMast.Columns .Add (m.Name ,m.GetType() );

}
//将对像的属性值加入到相应列中
DataRow DR=DT.NewRow ();
foreach(System.Reflection.PropertyInfo m in objType)
{
DR[m.Name ]=m.GetValue (this.FaceBillObj ,null);
}
DT.Rows .Add (DR);
}
}
现在的问题是,我是建立表的时候,DTPrintMast.Columns .Add (m.Name ,m.GetType() )这条语句,m.GetType()可能得到的是一个Users类型,再用DR[m.Name ]=m.GetValue (this.FaceBillObj ,null)给其赋值时会有问题,也就是说,这里存在一个对像A作为另一个对象B的属性的问题,我如何才能得到A的属性并将它们作为表的一列呢?不知道有没有说清楚,清请大家指教!

解决方案 »

  1.   

    提供一個思路,你看能不能Users  作為一個獨立的類,然後Bill裡面調用Users  
    通過屬性來把 Users   a = Bill.Users   然後對a作反射,訪問a裡面的屬性
      

  2.   

    谢谢 dragonfly001(),请各位帮帮忙看一下,分不够再加!顶者有分!
      

  3.   

    dragonfly001():我可能没有太明白你的意思,我现在能得到的,只是:public Bill objBill=new Bill ("testBill");  //单据对象 
    只有这一个单据对象,在实际项目中,objBill是基类的一个protected对象,为了利用多态,我只能在运行时能过objBill得到其中的各个子Field(有点像树中的叶结点,不过这里只有两层),我可能没有听懂你的意思,请解释详细一点,好吗?谢谢了!
      

  4.   

    private void button4_Click(object sender, System.EventArgs e)
    {
    ServerClass server = new ServerClass();
    System.Reflection.PropertyInfo[] properties = server.GetType().GetProperties(); foreach(System.Reflection.PropertyInfo m in properties)
    {
    dtTemp.Columns.Add(m.Name ,m.GetType());
    } foreach(System.Reflection.PropertyInfo m in properties)
    {
    System.Data.DataRow dr = dtTemp.NewRow();
    object obj = m.GetValue(server, null);;
    dr[m.Name] = obj;
    dtTemp.Rows.Add (dr);
    }
    }public class ServerClass
    {
    public int Show
    {
    get
    {
    return 0;
    }
    }
    }楼主自己看吧!
      

  5.   

    谢谢 hatita(悠远的风景):
     在你的基础上加个递归应该可以实现!谢谢
      

  6.   

    可能要寫個把對象類型->序列/反序列到一個string
      

  7.   

    谢谢 hatita(悠远的风景):这里还有个问题,System.Reflection.PropertyInfo[] properties = server.GetType().GetProperties();
    好像没有办法得到ServerClass类的基类中的属性,不知道有没有办法解决?
      

  8.   

    System.Reflection.PropertyInfo[] properties = server.GetType().GetProperties();
    可以得到所有的属性,包括基类中的,是我自己弄错了,结贴了,谢谢各位!