【转】反射,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;
}
}


优质内容筛选与推荐>>
1、.NET Framework 1.1安装出现1935错误的解决办法
2、面向对象分析与设计—四色原型模式(彩色建模、领域无关模型)(概念版)
3、opc数据采集并存入access数据库源代码 报表打印源代码
4、java File I/O
5、1-15


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号