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.

40 lines
1.3 KiB

1 year ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.AccessControl;
namespace ChangkeTec.Utils
{
public static class TransHelper<TIn, TOut>
{
private static readonly Func<TIn, TOut> Cache = GetFunc();
private static Func<TIn, TOut> GetFunc()
{
var parameterExpression = Expression.Parameter(typeof(TIn), "p");
var memberBindingList = new List<MemberBinding>();
foreach (var item in typeof(TOut).GetProperties())
{
if (!item.CanWrite) continue;
var inProp = typeof(TIn).GetProperty(item.Name);
if (inProp==null) continue;
var outProp = Expression.Property(parameterExpression, inProp);
MemberBinding memberBinding = Expression.Bind(item, outProp);
memberBindingList.Add(memberBinding);
}
var memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
var lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });
return lambda.Compile();
}
public static TOut Trans(TIn tIn)
{
return Cache(tIn);
}
}
}