public class People //类名 { private static string name; //字段 private string sex;//字段 public string Sex //属性 { get { return sex; } set { sex = value; } } public static string Name //属性 { get { return People.name; } set { People.name = value; } } }
class Program { static void Main(string[] args) { DataTable dt = new DataTable("dt"); GetTableByClass<People>(ref dt); Console.ReadKey(); } /// <summary> /// 反射类属性添加到DataTable /// </summary> /// <typeparam name="T">泛型类</typeparam> public static void GetTableByClass<T>(ref DataTable dt) { Type t = typeof(T); MemberInfo[] members = t.GetMembers(); List<string> ls = new List<string>(); foreach (MemberInfo member in members) { if (member.MemberType == MemberTypes.Property) { ls.Add(member.Name); } } AddArryFieldToTable(ref dt, ls); } /// <summary> /// 添加数组字段到DataTable /// </summary> public static void AddArryFieldToTable(ref DataTable dt, List<string> fieldNames) { foreach (string fieldName in fieldNames) { AddFieldToTable(ref dt, fieldName); } } /// <summary> /// 添加字段到DataTable /// </summary> public static void AddFieldToTable(ref DataTable dt, string fieldName) { DataColumn c = new DataColumn(); c.DataType = System.Type.GetType("System.String"); c.ColumnName = fieldName; dt.Columns.Add(c); } }