它应该是开箱即用的。字典不要求显式配置映射:
Dynamic and ExpandoObjects
是的。如果属性与我的示例中的相同,则类的属性也相同。
public class ObjA
{
public string Name { get; set; }
}
public class ObjB
{
public string Name { get; set; }
}
public class ClassA
{
public Dictionary<string, ObjA> Vals { get; set; } = new Dictionary<string, ObjA>{
{"a", new ObjA(){ Name = "A", } },
{"b", new ObjA(){ Name = "B", } },
{"c", new ObjA(){ Name = "C", } },
{"d", new ObjA(){ Name = "D", } },
};
}
public class ClassB
{
public Dictionary<string, ObjB> Vals { get; set; } = new Dictionary<string, ObjB>{
{"a", new ObjB(){ Name = "A", } },
{"b", new ObjB(){ Name = "B", } },
{"c", new ObjB(){ Name = "C", } },
{"d", new ObjB(){ Name = "D", } },
};
}
如果使用下面的automapper,映射应该自动工作。
var obja = new ClassA();
var objb = new ClassB();
var config = new MapperConfiguration(cfg => {});
var mapper = config.CreateMapper();
var obj = mapper.Map<ClassB>(obja);
var obj2 = mapper.Map<ClassA>(objb);
如果要硬编码类的映射,应该执行以下操作:
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<ClassA, ClassB>().ReverseMap();
});