直接上调用方法,实体结构不一样的时候只会转换字段名相同的,代码如下:
/// <summary>
/// 将一个实体对象转换为另一个实体对象
/// </summary>
/// <typeparam name="T1">第一个实体对象</typeparam>
/// <typeparam name="T2">第二个实体对象</typeparam>
/// <param name="source">转换的实体对象</param>
/// <returns></returns>
public static T2 CopyToModel<T1, T2>(T1 source)
{
T2 model = default(T2);
PropertyInfo[] pi = typeof(T2).GetProperties();
PropertyInfo[] pi1 = typeof(T1).GetProperties();
model = Activator.CreateInstance<T2>();
for (int i = 0; i < pi.Length; i++)
{
for (int j = 0; j < pi1.Length; j++)
{
if (pi[i].Name == pi1[j].Name)
{
pi[i].SetValue(model, pi1[j].GetValue(source, null), null);
}
}
}
return model;
}
传入实体对象及需要转换的实体,BackUp_HouseInfo及HouseInfo是两个不同的实体对象,下面是调用方法:
HouseInfo b_HouseInfo = data.ModelHouseInfo(IDText.Text.Trim()); //查询出来原来的内容值
BackUp_HouseInfo backUp_HouseInfo = new BackUp_HouseInfo(); //需要转换为某个实体对象实例
backUp_HouseInfo = ClassCode.CopyToModel<HouseInfo, BackUp_HouseInfo>(b_HouseInfo); //转换方法调用
评论列表: