我正在尝试构建一种从一种类型到另一种类型的映射方式,知道它们(应该)具有相同的结构。 Related Question
为了便于使用,我正在使用Codeplex的AutoMapper,具有以下功能:
private static List<Type> seenTypes = new List<Type>();
private static void MapDataObjects(Type a, Type b)
{
AutoMapper.Mapper.CreateMap(a, b);
PropertyInfo[] aProps = a.GetProperties();
PropertyInfo[] bProps = b.GetProperties();
foreach (PropertyInfo aProp in aProps)
{
if (aProp.PropertyType.Namespace.StartsWith("System")
|| seenTypes.Contains(aProp.PropertyType))
continue;
foreach (PropertyInfo bProp in bProps)
{
if (aProp.Name == bProp.Name)
{
MapDataObjects(aProp.PropertyType, bProp.PropertyType);
seenTypes.Add(aProp.PropertyType);
break;
}
}
}
}
在单步执行代码时似乎工作正常,但调用我的Map函数会出现以下错误:
AutoMapper.AutoMapperMappingException:
Trying to map TDXDataTypes.ClientActivity[] to ClientActivity[].
Using mapping configuration for TDXDataTypes.ClientActivity[] to ClientActivity[]
Destination property: Activities
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
---> System.ArgumentException:
Type 'ClientActivity[]' does not have a default constructor
答案 0 :(得分:1)
找到解决方案(在提出问题之前应该更加努力):
if (aProp.Name == bProp.Name)
{
if (aProp.PropertyType.IsArray)
{
MapDataObjects(aProp.PropertyType.GetElementType(), bProp.PropertyType.GetElementType());
seenTypes.Add(aProp.PropertyType.GetElementType());
break;
}
else
{
MapDataObjects(aProp.PropertyType, bProp.PropertyType);
seenTypes.Add(aProp.PropertyType);
break;
}
}