【转】反射,DataRow转换为实体类(优化)
修改为根据特性赋值,好处是数据库字段变化了,无需修改实体类属性,修改实体类属性很可能造成不必要的麻烦,所以改为用特性,特性的好处是数据库字段变化了只需要修改特性则可,不需要更改实体类属性
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
DataColumn dcName = new DataColumn("Name", typeof(string));
dt.Columns.Add(dcName);
DataRow row = dt.NewRow();
row["Name"] = "小强";
dt.Rows.Add(row);
Student s = new Student();
DataBind(s, dt.Rows[0]);
Console.WriteLine(s.StudentName);
}
static void DataBind(object entity, DataRow row)
{
Type type = entity.GetType();
PropertyInfo[] infors = type.GetProperties();
for (int i = 0; i < infors.Length; i++)
{
object[] attributes = infors[i].GetCustomAttributes(typeof(MyAttribute), false);
if (attributes.Length > 0)
{
MyAttribute attribute = attributes[0] as MyAttribute;
if (row.Table.Columns.Contains(attribute.Name))
{
object value = Convert.ChangeType(row[attribute.Name], infors[i].PropertyType);
infors[i].SetValue(entity, value, null);
}
}
}
}
}
public class Student
{
[My("Name")]
public string StudentName { get; set; }
}
[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{
public string Name { get; set; }
public MyAttribute(string name)
{
this.Name = name;
}
}