利用反射快速给Model实体赋值
2016-12-12 10:09
435 查看
public class BaseModel<T> where T : new() { public static T Init(DataRow dr) { T t = new T(); Type infotype = typeof(T); //获取所有属性 PropertyInfo[] propertys = infotype.GetProperties(); //遍历属性并将datarow中字段的值赋值给同名属性 foreach (PropertyInfo pi in propertys) { infotype.GetProperty(pi.Name).SetValue(t, result, null); } return t; } } BaseModel<Student>.Init(dr)
试想这样一个业务需求:有一张合同表,由于合同涉及内容比较多所以此表比较庞大,大概有120多个字段。现在合同每一次变更时都需要对合同原始信息进行归档一次,版本号依次递增。那么我们就要新建一张合同历史表,字段跟原合同表一模一样,此外多了一个 合同版本号 字段。在归档时如何把原始合同信息插入到合同历史表呢?
很容易就能想到的一种解决方法:
insert into 合同历史表(字段1,字段2,字段3…………字段120,版本号) select 字段1,字段2,字段3…………字段120,0 as 版本号 from 合同表 where 合同ID=‘xxxxxxx’
这样当然是能实现我们的功能的,但是看到了吗?由于表的字段太多,导致SQL看起来很不优雅,而且字段之间的对应很容易出问题。联想起之前看过的 利用反射给model赋值的例子想出来下面的一个解决方法:
现在假设两个实体class1、class2,class2只比class1多一个字段newid,其它字段一模一样。简单定义如下:
class Class1
{
private string id;
public string Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
private int num;
public int Num
{
get { return num; }
set { num = value; }
}
}
class Class2
{
private string newid;
public string Newid
{
get { return newid; }
set { newid = value; }
}
private string id;
public string Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
private int num;
public int Num
{
get { return num; }
set { num = value; }
}
}
下面我们给class1赋值,然后通过反射获取class2的属性,循环把class1对应的值赋给class2,遇到class2多出的字段我们手功处理后跳过。简单代码如下:
Class1 c1 = new Class1();
c1.Id = "001";
c1.Name = "ben.jiang";
c1.Num = 712104195;
c1.Age = 24;
Class2 c2 = new Class2();
Type t2 = typeof(Class2);
PropertyInfo[] propertys2 = t2.GetProperties();
Type t1 = typeof(Class1);
PropertyInfo[] propertys1 = t1.GetProperties();
foreach (PropertyInfo pi in propertys2)
{
string name = pi.Name;
if (name == "Newid")
{
c2.Newid = "newid";
continue;
}
object value=t1.GetProperty(name).GetValue(c1, null);
t2.GetProperty(name).SetValue(c2,value ,null);
}
这样代码看起来稍微优雅了一些,而且针对不同的字段我们处理起来也方便。
相关文章推荐
- 利用反射快速给Model实体赋值
- 利用反射快速给Model实体赋值
- 利用反射快速给Model实体赋值
- 利用反射快速给Model实体赋值(二)
- 【转】利用反射快速给Model实体赋值
- 利用反射把DataTable自动赋值到Model实体(自动识别数据类型)
- 利用反射把DataTable自动赋值到Model实体(自动识别数据类型)
- 利用反射把DataTable自动赋值到Model实体(自动识别数据类型)
- 利用反射快速给Model实体赋
- asp.net实现利用反射,泛型,静态方法快速获取表单值到Model的方法
- 利用反射,泛型,静态方法快速获取表单值到Model。(转)
- java 利用反射机制,获取实体所有属性和方法,并对属性赋值
- java 利用反射机制,获取实体所有属性和方法,并对属性赋值
- java 利用反射机制,获取实体所有属性和方法,并对属性赋值
- \t\t利用反射,泛型,静态方法快速获取表单值到Model
- 利用反射,泛型,静态方法快速获取表单值到Model。(Henq)
- java 利用反射机制,获取实体所有属性和方法,并对属性赋值
- java 利用反射机制,获取实体所有属性和方法,并对属性赋值
- java 利用反射机制,获取实体所有属性和方法,并对属性赋值
- java 利用反射机制,获取实体所有属性和方法,并对属性赋值