简体   繁体   English

清单的深层副本 <T> 使用扩展方法

[英]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. 当我在“立即窗口”中更改myCopy的值时,原始列表也将发生更改。

I'd like have both list completely independent 我想要两个列表完全独立

I missed something ? 我错过了什么?

Your implementation of Clone is wrong. 您对Clone实现是错误的。

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 除了Person类中Clone方法的问题之外,您还需要在扩展方法中返回一个新列表

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

This is because the Select method is from Linq which uses deferred execution. 这是因为Select方法来自使用延迟执行的Linq。 If you change the original list then the list of 'myCopy' will also change. 如果更改原始列表,则“ myCopy”的列表也会更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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