下面为实体类转换为DataTable的一个小例子:
用到了反射知识。
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Net_ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
User user = new User();
user.Name = "张三";
user.Age = 12;
user.Birthday = DateTime.Today;
DataTable dt = SetData<User>(user);
}
/// <summary>
/// 根据实体类得到表结构
/// </summary>
private static DataTable CreateTable<T>(T Modul)
{
//实例化一个表对象并设置表名
DataTable dataTable = new DataTable(typeof(T).Name);
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
dataTable.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType);
}
return dataTable;
}
/// <summary>
/// 把实体类转换为DataTable
/// </summary>
private static DataTable SetData<T>(T Modul)
{
DataTable dt = CreateTable<T>(Modul);
DataRow row = dt.NewRow();
foreach (PropertyInfo info in typeof(T).GetProperties())
{
row[info.Name] = info.GetValue(Modul);
}
dt.Rows.Add(row);
return dt;
}
}
/// <summary>
/// 实体类
/// </summary>
class User
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
}
}
原文:http://www.cnblogs.com/xiaochen0403/p/4234880.html