AutoMapper-开源的对象之间的映射工具
需要使用Nuget安装
1)命令行
PM> Install-Package AutoMapper
2)Nuget管理窗口查找然后安装
下面是两个例子。
1) 不含嵌套类的类之间映射
public class People { public string Name { get; set; } } public class Human { public string Name { get; set; } }
然后设置映射,转换。
public static void TestMapping() { Mapper.CreateMap<People, Human>(); Human h = Mapper.Map<Human>(new People { Name = "test" }); Console.WriteLine(h.Name); }
2)包含嵌套类的类之间的映射
public class People { public string Name { get; set; } public Contact Contact { get; set; } } public class Contact { public string Mobile { get; set; } public string Email { get; set; } } public class Human { public string Name { get; set; } public ContactDetail Contact { get; set; } } public class ContactDetail { public string Mobile { get; set; } public string Email { get; set; } }
需要为嵌套的每一个类设置映射(不只是第一层的类)
public static void TestNestedMapping() { Mapper.Initialize(cfg => { cfg.CreateMap<People, Human>(); cfg.CreateMap<Contact, ContactDetail>(); }); Human h = Mapper.Map<People, Human>(new People { Name = "test", Contact = new Contact { Mobile = "1231456", Email = "a@a.com" } }); var s = new XmlSerializer(typeof(Human)); using (StringWriter textWriter = new StringWriter()) { s.Serialize(textWriter, h); Console.WriteLine(textWriter.ToString()); } }
参考:

浙公网安备 33010602011771号