How do I clone a generic list in C#?

前端 未结 26 2507
失恋的感觉
失恋的感觉 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:09

    You can use extension method:

    namespace extension
    {
        public class ext
        {
            public static List clone(this List t)
            {
                List kop = new List();
                int x;
                for (x = 0; x < t.Count; x++)
                {
                    kop.Add(t[x]);
                }
                return kop;
            }
       };
    
    }
    

    You can clone all objects by using their value type members for example, consider this class:

    public class matrix
    {
        public List> mat;
        public int rows,cols;
        public matrix clone()
        { 
            // create new object
            matrix copy = new matrix();
            // firstly I can directly copy rows and cols because they are value types
            copy.rows = this.rows;  
            copy.cols = this.cols;
            // but now I can no t directly copy mat because it is not value type so
            int x;
            // I assume I have clone method for List
            for(x=0;x

    Note: if you do any change on copy (or clone) it will not affect the original object.

提交回复
热议问题