我遇到了这个问题,即使使用 CloneInjection 也无法复制具有相同名称和不同类型的属性。所以我在 CloneInjection 中更改了一些东西(我使用的是 ValueInjecter 版本 3.1.3)。
public class CloneInjection : LoopInjection
{
protected override void Execute(PropertyInfo sp, object source, object target)
{
var tp = target.GetType().GetProperty(sp.Name);
if (tp == null) return;
var val = sp.GetValue(source);
if (val == null) return;
tp.SetValue(target, GetClone(sp, tp, val));
}
private static object GetClone(PropertyInfo sp, PropertyInfo tp, object val)
{
if (sp.PropertyType.IsValueType || sp.PropertyType == typeof(string))
{
return val;
}
if (sp.PropertyType.IsArray)
{
var arr = val as Array;
var arrClone = arr.Clone() as Array;
for (int index = 0; index < arr.Length; index++)
{
var a = arr.GetValue(index);
if (a.GetType().IsValueType || a is string) continue;
arrClone.SetValue(Activator.CreateInstance(a.GetType()).InjectFrom<CloneInjection>(a), index);
}
return arrClone;
}
if (sp.PropertyType.IsGenericType)
{
//handle IEnumerable<> also ICollection<> IList<> List<>
if (sp.PropertyType.GetGenericTypeDefinition().GetInterfaces().Contains(typeof(IEnumerable)))
{
var genericType = tp.PropertyType.GetGenericArguments()[0];
var listType = typeof(List<>).MakeGenericType(genericType);
var list = Activator.CreateInstance(listType);
var addMethod = listType.GetMethod("Add");
foreach (var o in val as IEnumerable)
{
var listItem = genericType.IsValueType || genericType == typeof(string) ? o : Activator.CreateInstance(genericType).InjectFrom<CloneInjection>(o);
addMethod.Invoke(list, new[] { listItem });
}
return list;
}
//unhandled generic type, you could also return null or throw
return val;
}
return Activator.CreateInstance(tp.PropertyType)
.InjectFrom<CloneInjection>(val);
}
}
我是这样使用的:
var entityDto = new EntityDto().InjectFrom<CloneInjection>(sourceEntity);
我希望它有帮助!