怎样通过反射给嵌套的实体类属性赋值
C# code
/// <summary>
/// 实体转换辅助类
/// </summary>
public class ModelConvertHelper<T> where T : new()
{
public static IList<T> ConvertToModel(DataTable dt)
{
// 定义集合
IList<T> ts = new List<T>();
// 获得此模型的类型
Type type = typeof(T);
foreach (DataRow dr in dt.Rows)
{
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
// 检查DataTable是否包含此列
if (dt.Columns.Contains(pi.Name))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;
object value = dr[pi.Name];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
else
{
if ((pi.PropertyType).FullName.Contains("SMTModel.Model"))
{
ObjectHandle oh = Activator.CreateInstance("SMTModel", (pi.PropertyType).FullName);
object oo = oh.Unwrap();
//递归
//oo = ModelConvertHelper<oo>.ConvertToModel(dt)[0];
}
}
}
ts.Add(t);
}
return ts;
}
}
因为需求中实体类属性可能还有其他的实体类,所以想用反射加递归的方式来完成赋值,递归中这条//oo = ModelConvertHelper<oo>.ConvertToModel(dt)[0]; 不知道如何去写,还望高手指教= =
------解决方案--------------------
[C#]
public DataTable MakeDataTable(){
DataTable myTable;
DataRow myNewRow;
// Create a new DataTable.
myTable = new DataTable("My Table");
// Create DataColumn objects of data types.
DataColumn colString = new DataColumn("StringCol");
colString.DataType = System.Type.GetType("System.String");
myTable.Columns.Add(colString);
DataColumn colInt32 = new DataColumn("Int32Col");
colInt32.DataType = System.Type.GetType("System.Int32");
myTable.Columns.Add(colInt32);
DataColumn colBoolean = new DataColumn("BooleanCol");
colBoolean.DataType = System.Type.GetType("System.Boolean");
myTable.Columns.Add(colBoolean);
DataColumn colTimeSpan = new DataColumn("TimeSpanCol");
colTimeSpan.DataType = System.Type.GetType("System.TimeSpan");
myTable.Columns.Add(colTimeSpan);
DataColumn colDateTime = new DataColumn("DateTimeCol");
colDateTime.DataType = System.Type.GetType("System.DateTime");
myTable.Columns.Add(colDateTime);
DataColumn colDecimal = new DataColumn("DecimalCol");
colDecimal.DataType = System.Type.GetType("System.Decimal");
myTable.Columns.Add(colDecimal);
// Populate one row with values.
myNewRow = myTable.NewRow();
myNewRow["StringCol"] = "Item Name";
myNewRow["Int32Col"] = 2147483647;
myNewRow["BooleanCol"] = true;
myNewRow["TimeSpanCol"] = new TimeSpan(10,22,10,15,100);
myNewRow["DateTimeCol"] = System.DateTime.Today;
myNewRow["DecimalCol"] = 64.0021;
myTable.Rows.Add(myNewRow);
return myTable