You could使用 Reflection.Emit 来做到这一点,但它通常更容易使用Expression
s 并且它为您提供基本相同的性能。请记住,只有缓存已编译的代码(例如在Dictionary<Tuple<Type, Type>, Action<object, object>>
,我不在这里做。
static void Transfer(object source, object target)
{
var sourceType = source.GetType();
var targetType = target.GetType();
var sourceParameter = Expression.Parameter(typeof(object), "source");
var targetParameter = Expression.Parameter(typeof(object), "target");
var sourceVariable = Expression.Variable(sourceType, "castedSource");
var targetVariable = Expression.Variable(targetType, "castedTarget");
var expressions = new List<Expression>();
expressions.Add(Expression.Assign(sourceVariable, Expression.Convert(sourceParameter, sourceType)));
expressions.Add(Expression.Assign(targetVariable, Expression.Convert(targetParameter, targetType)));
foreach (var property in sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (!property.CanRead)
continue;
var targetProperty = targetType.GetProperty(property.Name, BindingFlags.Public | BindingFlags.Instance);
if (targetProperty != null
&& targetProperty.CanWrite
&& targetProperty.PropertyType.IsAssignableFrom(property.PropertyType))
{
expressions.Add(
Expression.Assign(
Expression.Property(targetVariable, targetProperty),
Expression.Convert(
Expression.Property(sourceVariable, property), targetProperty.PropertyType)));
}
}
var lambda =
Expression.Lambda<Action<object, object>>(
Expression.Block(new[] { sourceVariable, targetVariable }, expressions),
new[] { sourceParameter, targetParameter });
var del = lambda.Compile();
del(source, target);
}
如果你有这个,那么编写通用方法就很简单:
public TTarget Transfer<TSource, TTarget>(TSource source)
where TTarget : class, new()
{
var target = new TTarget();
Transfer(source, target);
return target;
}
让主工作方法变得通用并创建也是有意义的Action<TSource, TTarget>
,甚至让它直接创建对象并使用Func<TSource, TTarget>
。但如果按照我的建议添加缓存,则意味着您将不得不使用类似的东西Dictionary<Tuple<Type, Type>, Delegate>
并在从缓存中检索委托后将其转换为正确的类型。