调用 //获取一条User数据 UserModel model=GetUser(); //把UserModel类型转换成UserInfoModel类型 var userInfoModel = ModelTypeConvert.ConvertUserModel, UserInfoModel(model); 核心代码 /// summary /// 模型类型转换 /// /su
调用
//获取一条User数据
UserModel model=GetUser();
//把UserModel类型转换成UserInfoModel类型
var userInfoModel = ModelTypeConvert.Convert<UserModel, UserInfoModel>(model);
核心代码
/// <summary>
/// 模型类型转换
/// </summary>
public class ModelTypeConvert
{
/// <summary>
/// 模型类型转换,OutT的属性必须和InT的属性类型和属性名称一致
/// </summary>
/// <typeparam name="InT">进入的类型</typeparam>
/// <typeparam name="OutT">转换后的类型</typeparam>
/// <param name="inT">进入的类型</param>
/// <returns></returns>
public static OutT Convert<InT, OutT>(InT inT)
{
Type InType = typeof(InT);
InT inTModel = inT;
Type OutType = typeof(OutT);
OutT outTModel = (OutT)Activator.CreateInstance(OutType);
//通过反射去遍历属性
foreach (PropertyInfo inProperty in InType.GetProperties())
{
foreach (PropertyInfo OutProperty in OutType.GetProperties())
{
if (inProperty.Name== OutProperty.Name && inProperty.PropertyType == OutProperty.PropertyType)
{
OutProperty.SetValue(outTModel, inProperty.GetValue(inTModel));
}
}
}
return outTModel;
}
}