Java clone() in C#
本文关键字:in clone Java | 更新日期: 2023-09-27 18:37:25
我正在将代码从Java重写为C#。我在 C# 中的克隆函数有问题。
代码输入爪哇岛:
public Tour(ArrayList tour)
{
this.tour = (ArrayList) tour.clone();
}
我的代码在C#:
public Tour(List<City> tour)
{
//What I should do here?
}
我尝试了一些在 C# 中克隆的技术,但没有结果。
编辑:
此解决方案完美运行:
this.tour = new List<City>();
tour.ForEach((item) =>
{
this.tour.Add(new City(item));
});
问候!

java.util.ArrayList.clone()返回此 ArrayList 实例的浅表副本(即不复制元素本身)。
--源
在 中执行相同的操作。NET List<T>你可以做的:
var newList = oldList.ToList();
你应该在City类上实现ICloneable。
这样你就可以这样做:
public List<City> Tour {get; private set;}
public Tour(List<City> tour)
{
this.Tour = new List<City>();
foreach (var city in tour)
this.tour.Add((City)city.Clone());
}