一个web程序引用了  sql.dll类库 
这个类库中有一个类的方法(参数是web程序的model类)  是通过反射获取 web程序集的一个model层的一个类  
而且这个sql。dll类库还负责从数据库查询数据。 
请问现在我要求sql.ll中的一个方法可以把查询到的数据封装到model层的一个类的对象中,该如何实现? 一下是部分代码 
            Assembly asm = Assembly.LoadFile("F:\\Selliter\\demandsql\\sqltest\\bin\\Debug\\sql.dll"); 
            
    
              Type t = asm.GetType("sqltest.Tb_User"); 
            PropertyInfo[] pi = t.GetProperties();       DataTable dtu= SelliterList.Select(u.GetType()); 
          } 
        foreach (DataRow dr in dtu.Rows) 
          { 
            如何写?? 
          } 
        

解决方案 »

  1.   

    假设你通过反射创建的对象叫obj;
    取到数据后,找到对应的属性(PropertyInfo pi)
    然后这样pi.SetValue(obj,取到的数据,null);
      

  2.   

       Type t = asm.GetType("sqltest.Tb_User");
              // PropertyInfo[] pi = t.GetProperties();            DataTable dtu = SelliterList.Select(u.GetType());           
                IList<object> _ObjectList =new List<object>();
                foreach (DataRow dr in dtu.Rows)
                {
                     object _Object = System.Activator.CreateInstance(t, new object[] { });                for(int i=0;i!=dtu.Columns.Count;i++)
                    {
                        PropertyInfo _Property = t.GetProperty(dtu.Columns[i].ColumnName);
                        _Object = Convert.ChangeType(_Object, _Property.PropertyType);
                        if (_Property != null) _Property.SetValue(_Object, dr[dtu.Columns[i].ColumnName], new object[] { });
                    }
                    _ObjectList.Add(_Object);
                }
      

  3.   

    上楼麻烦你把代码  for循环里面的每一行都解释一下,告诉我是做什么的。  我就给你满分。
      

  4.   

    object _Object = System.Activator.CreateInstance(t, new object[] { }); //创建sqltest.Tb_User实例                for(int i=0;i!=dtu.Columns.Count;i++) //为实例赋值
                    { 
                        PropertyInfo _Property = t.GetProperty(dtu.Columns[i].ColumnName); //根据列名得到sqltest.Tb_User类属性
                        _Object = Convert.ChangeType(_Object, _Property.PropertyType); 
                        if (_Property != null) _Property.SetValue(_Object, dr[dtu.Columns[i].ColumnName], new object[] { }); //为属性赋值
                    } 
                    _ObjectList.Add(_Object); //将实例添加到List
      

  5.   

    我的属性名称是固定不边的,但不是从数据库中查出来的。。
    PropertyInfo _Property = t.GetProperty(dtu.Columns[i].ColumnName);
    这句话是找不到我的属性的。