Mapping items from one class to another if Items are equivalent

前端 未结 4 1367
鱼传尺愫
鱼传尺愫 2021-01-16 02:53

Say I have one class that looks like this:

public class Person
{
     public string Name {get; set;}
     public int Number {get; set;}
}
         


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-16 03:26

    You can use AutoMapper:

    public Dog UsingAMR(Person prs)
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap();
        });
        IMapper mapper = config.CreateMapper();
        return mapper.Map(prs);
    }
    

    Then you can easily:

    Person ps = new Person {Name = "John", Number = 25};
    Dog dog = UsingAMR(ps);
    

    Just don't forget to install AutoMapper first from the package manager console as mentioned in the reference:

    1. From Tools menu click on NuGet Package Manager ==> Package Manager Console
    2. Then type the following command:

      PM> Install-Package AutoMapper
      

提交回复
热议问题