Reputation: 333
I'm trying to perform a deep copy of an object in C# so when I do the following:
Route currentBestRoute = Ants[0].Route;
currentBestRoute would not change after altering Ants[0].Route.
I have tried altering the Route 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;
}
}
}
and conduct a deep clone as below:
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;
}
But this is not working. currentBestRoute still changes on its own every time the Ants List is updated.
Am I missing something?
Upvotes: 1
Views: 334
Reputation: 273244
public object Clone()
{
Route route = new Route
{
//Cities = Cities
Cities = this.Cities.ToList(),
};
return route;
}
Upvotes: 2
Reputation: 196
IConeable interface doesn't create deep copy. you can use [Serializable] attribute on class and use this generic code
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);
}
}
Upvotes: 0