泛型反反射方法显示

public List<T> Query<T>(string where) where T : class, new()
{
DataTable tb = new DataTable();
List<T> list = new List<T>();
string sql = GetQuery();
sql += where;
//反射
using (SqlConnection con = new SqlConnection(LIANJIE))
{
con.Open();
using (SqlCommand com=new SqlCommand(sql,con))
{
SqlDataAdapter adapter = new SqlDataAdapter(com);
adapter.Fill(tb);
//获取Type类型
Type type = typeof(T);
//循环行
for (int i = 0; i < tb.Rows.Count; i++)
{
//相当于实例化
object obj = Activator.CreateInstance(type);
for (int j = 0; j < tb.Columns.Count; j++)
{
PropertyInfo info = type.GetProperty(tb.Columns[j].ColumnName);
//判断类型 int
if (tb.Columns[j].DataType==typeof(Int32))
{
//判断是否有空值
if (tb.Rows[i][j]!=null)
{
info.SetValue(obj, int.Parse(tb.Rows[i][j].ToString()),null);
}
else
{
info.SetValue(obj,0,null);
}
}
//float
else if (tb.Columns[j].DataType==typeof(float))
{
//判断值是否为空
if (tb.Rows[i][j]!=null)
{
info.SetValue(obj,float.Parse( tb.Rows[i][j].ToString()),null);
}
else
{
info.SetValue(obj,0.0,null);
}

}
//datatime
else if (tb.Columns[j].DataType==typeof(DateTime))
{
//判断不为空
if (tb.Rows[i][j]!=null)
{
info.SetValue(obj, DateTime.Parse(tb.Rows[i][j].ToString()), null);
}
else
{
info.SetValue(obj,DateTime.Now,null);
}
}
//double
else if (tb.Columns[j].DataType==typeof(double))
{
if (tb.Rows[i][j]!=null)
{
info.SetValue(obj,double.Parse(tb.Rows[i][j].ToString()),null);

}
else
{
info.SetValue(obj,0.0,null);
}
}
//string
else
{
if (tb.Rows[i][j]!=null)
{
info.SetValue(obj,tb.Rows[i][j].ToString(),null);
}
else
{
info.SetValue(obj,"",null);
}
}

}
//保险起见强转一下
list.Add((T)obj);
}


}
}

return list;
}

posted @ 2020-06-15 20:59  孔捷  阅读(172)  评论(0编辑  收藏  举报