Copy object to object (with Automapper ?)

前端 未结 5 1883
[愿得一人]
[愿得一人] 2020-11-30 04:16

I have a class:

public class Person {
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

I have two insta

5条回答
  •  一生所求
    2020-11-30 04:55

    Since you asked With Automapper? can I suggest you don't use AutoMapper?

    Instead use MemberwiseClone() in a Clone method, e.g.

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        public Person Clone()
        {
            return (Person) MemberwiseClone();
        }
    }
    

    UPDATE

    Its important to note this does not acheive the original posters desire to copy person1 into person2

    However, (and as @Jimmy Bogard points out) using MemberwiseClone() is preferred if you just need to make a copy (clone) of the object.

    For instance, if you are doing this:

    //I need a copy of person1 please! I'll make a new person object 
    //and automapper everything into it!
    var person2 = new Person2();
    Mapper.Map(person1, person2)
    

    then really you should/could use

    //oh wait, i can just use this!
    var person2 = person1.Clone()
    

提交回复
热议问题