>  기사  >  백엔드 개발  >  C#에서 List 개체의 전체 복사 문제를 간략하게 소개합니다.

C#에서 List 개체의 전체 복사 문제를 간략하게 소개합니다.

黄舟
黄舟원래의
2017-03-29 11:32:421684검색

다음 편집자는 C#List8742468051c85b06f0a0af9e3e506b5c객체 의 전체 복사 문제에 대해 간략하게 설명합니다. 에디터가 꽤 좋다고 생각해서 지금 공유해서 참고용으로 올려보겠습니다. 에디터를 따라가서 함께 살펴볼까요

1. List8742468051c85b06f0a0af9e3e506b5c 객체의 T가 값 유형(int 유형 등)인 경우

값 유형 목록의 경우 다음 방법으로 직접 복사할 수 있습니다.

List<T> oldList = new List<T>(); 
oldList.Add(..); 
List<T> newList = new List<T>(oldList);

2. List8742468051c85b06f0a0af9e3e506b5c 개체의 T가 참조 유형인 경우 (예: 사용자 정의 엔터티 클래스)

1. 위의 방법은 List에 있는 개체의 참조만 복사할 수 있습니다. 복사하려면 다음 확장 방법을 사용하십시오.

static class Extensions 
 { 
     public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable 
     { 
         return listToClone.Select(item => (T)item.Clone()).ToList(); 
     } 
 //当然前题是List中的对象要实现ICloneable接口
 }

2. 직렬화를 사용하여 참조 객체의 전체 복사를 완료하는 또 다른 방법은 가장 신뢰할 수 있는

public static T Clone<T>(T RealObject) 

{ 
   using (Stream objectStream = new MemoryStream()) 
   { 
      //利用 System.Runtime.Serialization序列化与反序列化完成引用对象的复制
       IFormatter formatter = new BinaryFormatter(); 
       formatter.Serialize(objectStream, RealObject); 
       objectStream.Seek(0, SeekOrigin.Begin); 
       return (T)formatter.Deserialize(objectStream); 
   } 
}

방법입니다. Xml.직렬화 및 역직렬화 구현

public static T Clone<T>(T RealObject) 
{ 
      using(Stream stream=new MemoryStream())
      {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        serializer.Serialize(stream, RealObject);
        stream.Seek(0, SeekOrigin.Begin);
        return (T)serializer.Deserialize(stream);
      }
}

3. 위 개체의 전체 복사본을 테스트합니다.

테스트는 다음과 같습니다:

using System;
using System.Collections.Generic;
using System.Collections ;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace LINQ
{
  [Serializable]
  public class tt
  {
    private string name = "";

    public string Name
    {
      get { return name; }
      set { name = value; }
    }
    private string sex = "";

    public string Sex
    {
      get { return sex; }
      set { sex = value; }
    }
  }

  class LINQTest
  {
    public static T Clone<T>(T RealObject) 
    { 
      using (Stream objectStream = new MemoryStream()) 
      { 
        IFormatter formatter = new BinaryFormatter(); 
        formatter.Serialize(objectStream, RealObject); 
        objectStream.Seek(0, SeekOrigin.Begin); 
        return (T)formatter.Deserialize(objectStream); 
      } 
    }


    public static void Main()
    {
      List<tt> lsttt = new List<tt>();
      tt tt1 = new tt();
      tt1.Name = "a1";
      tt1.Sex = "20";
      lsttt.Add(tt1);
      List<tt> l333 = new List<tt>();
      l333.Add(Clone<tt>(lsttt[0]));
      l333[0].Name = "333333333";
   }
 }
}

위 내용은 C#에서 List 개체의 전체 복사 문제를 간략하게 소개합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.