C# Datatable 转实体对象
DataTable dt = new DataTable(); dt.Columns.Add("Name"); dt.Columns.Add("Age"); DataRow dr1 = dt.NewRow(); dr1["Name"] = "a"; dr1["Age"] = 1 ; dt.Rows.Add(dr1); Student s = new Student(); Type info = typeof(Student); foreach(var mi in info.GetMembers()) { if(mi.MemberType==MemberTypes.Property) { var p = info.GetProperty(mi.Name); p.SetValue(s, Convert.ChangeType(dt.Rows[0][mi.Name], p.PropertyType), null); } }
1 public class Student { 2 [DataField("Name")] 3 public string Name { get; set; } 4 [DataField("Age")] 5 public int Age { get; set; } 6 } 7 [AttributeUsage(AttributeTargets.Property)] 8 public class DataField:Attribute 9 { 10 public string ColumnName { get; set; } 11 12 public DataField(string columnName) 13 { 14 ColumnName = columnName; 15 } 16 }
鹰击长空,鱼翔浅底