C#对象的深层副本 [英] Deep Copy of a C# Object

查看:82
本文介绍了C#对象的深层副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些用C#编写的代码。在此应用程序中,我有一个定义如下的自定义集合:

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<T> : IEnumerable<T>
{
  public List<T> Results { get; set; }
  public decimal CenterLatitude { get; set; }
  public decimal CenterLongitude { get; set; }
}

Results使用的类型是三种自定义类型之一。每个自定义类型的属性都只是原始类型(int,字符串,bools,int?,bool?)。这是自定义类型之一的示例:

The type used by Results are one of three custom types. The properties of each of the custom types are just primitive types (ints, strings, bools, int?, bool?). Here is an example of one of the custom types:

public class ResultItem
{
  public int ID { get; set; }
  public string Name { get; set; }
  public bool? isLegit { get; set; }
}

如何对我已执行的ResultList对象执行深层复制创建。我找到了这篇文章:创建集合中所有元素的深层副本。但是,我不知道该怎么做。

How do I perform a deep copy of a ResultList object that I've created. I found this post: Generic method to create deep copy of all elements in a collection. However, I can't figure out how to do it.

推荐答案

您的ResultList类不适用于Jon Skeet的示例,因为它没有实现ICloneable接口。

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.

在需要克隆的所有类上都实现Iloneable,例如

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;
  }
}

以及在ResultList上:

And also on ResultList:

public class ResultList<T> : IEnumerable<T>, ICloneable where T : ICloneable
{
  public List<T> Results { get; set; }
  public decimal CenterLatitude { get; set; }
  public decimal CenterLongitude { get; set; }

  public object Clone()
  {
    var list = new ResultList<T>
                 {
                   CenterLatitude = CenterLatitude,
                   CenterLongitude = CenterLongitude,
                   Results = Results.Select(x => x.Clone()).Cast<T>().ToList()
                 };
    return list;
  }
}

然后制作对象的深层副本:

Then to make a deep copy of your object:

resultList.clone();

这篇关于C#对象的深层副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆