如何进行正确的深拷贝?

How to conduct proper deep copying?

我正在尝试在 C# 中执行对象的深层复制,所以当我执行以下操作时:

Route currentBestRoute = Ants[0].Route;

改变 Ants[0].Route 后,currentBestRoute 不会改变。

我试过改变路线 class:

using System;
using System.Collections.Generic;

namespace ACO.Models
{

    public class Route : ICloneable
    {

        public List<City> Cities = new List<City>();
        public string Name
        {
            get
            {
                string name = "";

                for(int i = 0; i < Cities.Count; i++)
                {
                    name += Cities[i].Name;

                    if (i != Cities.Count - 1)
                    {
                        name += "->";
                    }
                }
                return name;

            }
        }
        public double Distance
        {
            get
            {
                double distance = 0.0;

                for(int i = 0; i < Cities.Count - 1; i++)
                {
                    distance += Cities[i].measureDistance(Cities[i + 1]);
                }

                return distance;
            }

        }

        public object Clone()
        {
            Route route = new Route
            {
                Cities = Cities
            };
            return route;
        }
    }
}

并进行深度克隆如下:

 private static Route GetCurrentBestRoute()
        {
            Route currentBestRoute = (Route) Ants[0].Route.Clone();

            foreach(Ant ant in Ants)
            {
                if(ant.Route.Distance < currentBestRoute.Distance)
                {
                    currentBestRoute = (Route) ant.Route.Clone();
                }
            }

            return currentBestRoute;
        }

但这不起作用。每次更新蚂蚁列表时,currentBestRoute 仍然会自行更改。

我错过了什么吗?

public object Clone()
{
    Route route = new Route
    {
        //Cities = Cities
          Cities = this.Cities.ToList(),
    };
    return route;
}

IConeable 接口不创建深拷贝。您可以在 class 上使用 [Serializable] 属性 并使用这个通用代码

public static T DeepClone<T>(T obj)
{
     using (var ms = new MemoryStream())
     {
         var formatter = new BinaryFormatter();
         formatter.Serialize(ms, obj);
         ms.Position = 0;

         return (T) formatter.Deserialize(ms);
      }
}