考虑使用Automapper使用定义的配置或某种约定将一个自定义实例转换为另一个。如果它们具有相同的名称和类型兼容,则它具有映射属性的约定,默认情况下可以使用。接下来的代码演示了它的用法
void Main()
{
List<UserMaster> users = new List<UserMaster>{
new UserMaster{Name = "Bob", Email = "bob@mail.ru", Salary = 10},
new UserMaster{Name = "Jack", Email = "jack@mail.ru", Salary = 20},
new UserMaster{Name = "John", Email = "john@mail.ru", Salary = 40},
};
Mapper.CreateMap<UserMaster, UserMasterTemp>();
List<UserMasterTemp> usersTemp = Mapper.Map<IEnumerable<UserMaster>,
List<UserMasterTemp>>(users);
usersTemp.ForEach(Console.WriteLine);
}
class UserMaster
{
public string Name { get; set; }
public string Email { get; set; }
public decimal Salary { get; set; }
}
class UserMasterTemp
{
public string Name { get; set; }
public string Email { get; set; }
public decimal Salary { get; set; }
//formating for demo purposes
public override string ToString()
{
return string.Format("Name: {0}, Email: {1}, Salary: {2}",
Name, Email, Salary);
}
}
印刷:
Name: Bob, Email: bob@mail.ru, Salary: 10
Name: Jack, Email: jack@mail.ru, Salary: 20
Name: John, Email: john@mail.ru, Salary: 40