C#公共类
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.7 KiB

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Common.Helper.Entity
{
public class ModelToEntity<TM,TE>
{
/// <summary>
/// 类型转换,有则赋值,没有则默认值 这个可以不传需要转换的值
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static TE Change(TM model)
{
var modelPropertyInfos = typeof(TM).GetProperties();
var entityType = typeof(TE);
var entity =(TE)Activator.CreateInstance(typeof(TE));
foreach (var modelPropertyInfo in modelPropertyInfos)
{
if(entityType.GetProperty(modelPropertyInfo.Name)!=null)
entityType.GetProperty(modelPropertyInfo.Name)?.SetValue(entity, modelPropertyInfo.GetValue(model), null);
}
return entity;
}
/// <summary>
/// 类型转换,只是这个可以传入需要转换的值
/// </summary>
/// <param name="model"></param>
/// <param name="entity"></param>
/// <returns></returns>
public static TE Set(TM model,TE entity)
{
var modelPropertyInfos = typeof(TM).GetProperties();
var entityType = typeof(TE);
foreach (var modelPropertyInfo in modelPropertyInfos)
{
if (entityType.GetProperty(modelPropertyInfo.Name) != null)
entityType.GetProperty(modelPropertyInfo.Name)?.SetValue(entity, modelPropertyInfo.GetValue(model), null);
}
return entity;
}
}
}