How do I clone a generic list in C#?

前端 未结 26 2767
失恋的感觉
失恋的感觉 2020-11-22 01:27

I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn\'t seem to be an option to do list.Clone()

26条回答
  •  野的像风
    2020-11-22 02:08

    I'll be lucky if anybody ever reads this... but in order to not return a list of type object in my Clone methods, I created an interface:

    public interface IMyCloneable
    {
        T Clone();
    }
    

    Then I specified the extension:

    public static List Clone(this List listToClone) where T : IMyCloneable
    {
        return listToClone.Select(item => (T)item.Clone()).ToList();
    }
    

    And here is an implementation of the interface in my A/V marking software. I wanted to have my Clone() method return a list of VidMark (while the ICloneable interface wanted my method to return a list of object):

    public class VidMark : IMyCloneable
    {
        public long Beg { get; set; }
        public long End { get; set; }
        public string Desc { get; set; }
        public int Rank { get; set; } = 0;
    
        public VidMark Clone()
        {
            return (VidMark)this.MemberwiseClone();
        }
    }
    

    And finally, the usage of the extension inside a class:

    private List _VidMarks;
    private List _UndoVidMarks;
    
    //Other methods instantiate and fill the lists
    
    private void SetUndoVidMarks()
    {
        _UndoVidMarks = _VidMarks.Clone();
    }
    

    Anybody like it? Any improvements?

提交回复
热议问题