Deep Copy of a C# Object

后端 未结 4 734
梦毁少年i
梦毁少年i 2020-12-17 00:44

I am working on some code that is written in C#. In this app, I have a custom collection defined as follows:

public class ResultList : IEnumerable&l         


        
4条回答
  •  眼角桃花
    2020-12-17 01:12

    One of the reasons why your ResultList class won't work with Jon Skeet's example is because it does not implement the ICloneable interface.

    Implement ICloneable on all the classes that you need cloned, e.g.

    public class ResultItem : ICloneable
    {
      public object Clone()
      {
        var item = new ResultItem
                     {
                       ID = ID,
                       Name = Name,
                       isLegit = isLegit
                     };
        return item;
      }
    }
    

    And also on ResultList:

    public class ResultList : IEnumerable, ICloneable where T : ICloneable
    {
      public List Results { get; set; }
      public decimal CenterLatitude { get; set; }
      public decimal CenterLongitude { get; set; }
    
      public object Clone()
      {
        var list = new ResultList
                     {
                       CenterLatitude = CenterLatitude,
                       CenterLongitude = CenterLongitude,
                       Results = Results.Select(x => x.Clone()).Cast().ToList()
                     };
        return list;
      }
    }
    

    Then to make a deep copy of your object:

    resultList.clone();
    

提交回复
热议问题