简体   繁体   中英

Deep copy of List<T> with extension method

I have this class :

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

    public object Clone()
    {
        return this;
    }
}

An extension method :

public static class MyHelper
{
    public static IEnumerable<T> Clone<T>(this IEnumerable<T> collection) where T : ICloneable
    {
        return collection.Select(item => (T)item.Clone());
    }
}

I'd like use it in this case :

var myList = new List<Person>{ 
    new Person { FirstName = "Dana", LastName = "Scully" },
    new Person{ FirstName = "Fox", LastName = "Mulder" }
};

List<Person> myCopy = myList.Clone().ToList<Person>();

When I change in the "immediat window" a value of myCopy , there is a change in the orginial list too.

I'd like have both list completely independent

I missed something ?

Your implementation of Clone is wrong.

Try this:

public object Clone()
{
    return MemberwiseClone();
}

Your clone method returns the same object.

You should implement it like this

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

    public object Clone()
    {
        return new Person { FirstName = this.FirstName, LastName = this.LastName };
    }
}

Apart from the issue with your Clone method inside your Person class you need to return a new list in your extension method also

return collection.Select(item => (T)item.Clone()).ToList();

This is because the Select method is from Linq which uses deferred execution. If you change the original list then the list of 'myCopy' will also change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM