嗯,我有一个
真的很可怕
你能做到的方式。
你可以编写一个方法,使用反射(请耐心听我说!)来计算特定类型的所有属性,并构建一个委托(使用reflection.Emit)将属性从该类型复制到另一个类型。然后使用匿名类型来确保您只需要构建一次复制委托,因此速度很快。你的方法看起来像这样:
public static Expression<Func<Foo, FooEditDto>> EditDtoSelector()
{
return f => MagicCopier<FooEditDto>.Copy(new {
f.PropertyA, f.PropertyB, f.PropertyC, f.PropertyD, f.PropertyC
});
}
这里的细微差别:
-
MagicCopier是泛型类型,Copy是泛型方法,因此您可以显式指定“目标”类型,但隐式指定“源”类型。
-
它使用投影初始化器从用于初始化匿名类型的表达式中推断属性的名称
我不确定这是否真的值得,但这是一个很有趣的想法。..我可能无论如何都要实现它:)
编辑:与
MemberInitExpression
我们可以用表达式树来完成这一切,这比CodeDOM容易得多。今晚我会试试。..
编辑:完成了,这实际上是一段非常简单的代码。这是课堂:
/// <summary>
/// Generic class which copies to its target type from a source
/// type specified in the Copy method. The types are specified
/// separately to take advantage of type inference on generic
/// method arguments.
/// </summary>
public static class PropertyCopy<TTarget> where TTarget : class, new()
{
/// <summary>
/// Copies all readable properties from the source to a new instance
/// of TTarget.
/// </summary>
public static TTarget CopyFrom<TSource>(TSource source) where TSource : class
{
return PropertyCopier<TSource>.Copy(source);
}
/// <summary>
/// Static class to efficiently store the compiled delegate which can
/// do the copying. We need a bit of work to ensure that exceptions are
/// appropriately propagated, as the exception is generated at type initialization
/// time, but we wish it to be thrown as an ArgumentException.
/// </summary>
private static class PropertyCopier<TSource> where TSource : class
{
private static readonly Func<TSource, TTarget> copier;
private static readonly Exception initializationException;
internal static TTarget Copy(TSource source)
{
if (initializationException != null)
{
throw initializationException;
}
if (source == null)
{
throw new ArgumentNullException("source");
}
return copier(source);
}
static PropertyCopier()
{
try
{
copier = BuildCopier();
initializationException = null;
}
catch (Exception e)
{
copier = null;
initializationException = e;
}
}
private static Func<TSource, TTarget> BuildCopier()
{
ParameterExpression sourceParameter = Expression.Parameter(typeof(TSource), "source");
var bindings = new List<MemberBinding>();
foreach (PropertyInfo sourceProperty in typeof(TSource).GetProperties())
{
if (!sourceProperty.CanRead)
{
continue;
}
PropertyInfo targetProperty = typeof(TTarget).GetProperty(sourceProperty.Name);
if (targetProperty == null)
{
throw new ArgumentException("Property " + sourceProperty.Name
+ " is not present and accessible in " + typeof(TTarget).FullName);
}
if (!targetProperty.CanWrite)
{
throw new ArgumentException("Property " + sourceProperty.Name
+ " is not writable in " + typeof(TTarget).FullName);
}
if (!targetProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
throw new ArgumentException("Property " + sourceProperty.Name
+ " has an incompatible type in " + typeof(TTarget).FullName);
}
bindings.Add(Expression.Bind(targetProperty, Expression.Property(sourceParameter, sourceProperty)));
}
Expression initializer = Expression.MemberInit(Expression.New(typeof(TTarget)), bindings);
return Expression.Lambda<Func<TSource,TTarget>>(initializer, sourceParameter).Compile();
}
}
并称之为:
TargetType target = PropertyCopy<TargetType>.CopyFrom(new { First="Foo", Second="Bar" });