C#의 List 객체 복제본

2878 단어 DOTNET
1. List 객체의 T가 값 유형인 경우(int 유형 등)
List oldList = new List(); 
oldList.Add(..); 
List newList = new List(oldList); 

2. List 객체의 T가 참조 유형인 경우(예: 사용자 정의 솔리드 클래스)
1. 인용 유형의 리스트는 상기 방법으로 복제할 수 없고 리스트에 있는 대상의 인용만 복제할 수 있으며 다음과 같은 확장 방법으로 복제할 수 있다.
 List ICloneable 
using System.Linq;

namespace NvcMall.Core
{
    /// 
    ///  
    /// 
    public class CommonHelper
    {   
        public static IList Clone(this IList listToClone) where T : ICloneable
        {
            return listToClone.Select(item => (T)item.Clone()).ToList();
        } 
    }
}

2. 인용 대상을 서열화하는 또 다른 방법이 가장 믿을 만하다.
using System.Linq;

namespace NvcMall.Core
{
    /// 
    ///  
    /// 
    public class CommonHelper
    {  
        /// 
        ///  
        /// 
        /// 
        /// 
        /// 
        public static T Clone(T RealObject)
        { 
            using (Stream objStream = new MemoryStream())
            {
                //  System.Runtime.Serialization 
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objStream, RealObject);
                objStream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(objStream);
            }

        }
        /// 
        ///  
        /// 
        /// 
        /// 
        /// 
        public static List Clone(List RealObject)
        {  
            using (Stream objStream = new MemoryStream())
            {
                //  System.Runtime.Serialization 
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objStream, RealObject);
                objStream.Seek(0, SeekOrigin.Begin);
                return (List)formatter.Deserialize(objStream);
            }

        }

       
    }
}

클래스는 [serializable] [serializable] public class 클래스 이름을 넣어야 합니다.
3. System을 이용한다.Xml.Serialization을 통해 서열화와 반서열화를 실현하다
 public static T Clone(T RealObject)
        {
            using (Stream stream = new MemoryStream())
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                serializer.Serialize(stream, RealObject);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)serializer.Deserialize(stream);
            }
        }

2. List 객체의 T가 참조 유형인 경우(예: 사용자 정의 솔리드 클래스)

좋은 웹페이지 즐겨찾기