62 lines
2.1 KiB
C#
62 lines
2.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace WX.CRM.Common
|
|
{
|
|
public class CopyInofHelper
|
|
{
|
|
/// <summary>
|
|
/// 类型转换
|
|
/// </summary>
|
|
/// <typeparam name="T">原类型</typeparam>
|
|
/// <typeparam name="R">目标类型</typeparam>
|
|
/// <param name="obj"></param>
|
|
/// <returns></returns>
|
|
public static R ToResult<T, R>(T obj) where R : new()
|
|
{
|
|
R t = new R();
|
|
var props = typeof(T).GetProperties().Where(a => a.CanRead && a.CanWrite);
|
|
foreach (var item in props)
|
|
{
|
|
item.SetValue(t, item.GetValue(obj, null), null);
|
|
}
|
|
return t;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 从父类到子类转换
|
|
/// </summary>
|
|
/// <typeparam name="TP">父类</typeparam>
|
|
/// <typeparam name="TC">子类</typeparam>
|
|
/// <param name="parent"></param>
|
|
/// <returns></returns>
|
|
public static TC CopyFromParent<TP, TC>(TP parent) where TC : TP, new() where TP : new()
|
|
{
|
|
if (parent == null) return default(TC);
|
|
var child = new TC();
|
|
typeof(TP).GetProperties().Where(p => p.CanRead && p.CanWrite).ToList()
|
|
.ForEach(p => p.SetValue(child, p.GetValue(parent, null), null));
|
|
return child;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 从子类到父类
|
|
/// </summary>
|
|
/// <typeparam name="TP">父类</typeparam>
|
|
/// <typeparam name="TC">子类</typeparam>
|
|
/// <param name="child"></param>
|
|
/// <returns></returns>
|
|
public static TP CopyToParent<TP, TC>(TC child) where TC : TP, new() where TP : new()
|
|
{
|
|
if (child == null) return default(TP);
|
|
var parent = new TP();
|
|
typeof(TP).GetProperties().Where(p => p.CanRead && p.CanWrite).ToList()
|
|
.ForEach(p => p.SetValue(parent, p.GetValue(child, null), null));
|
|
return parent;
|
|
}
|
|
}
|
|
}
|