如何克隆Collection< T> ;? [英] How do I clone a Collection<T>?
问题描述
我有一个枚举 Fruit
和一个类 FruitCollection
,该类派生了集合<水果>
。我找不到使用.NET克隆 FruitCollection
的方法,我发现了此MSDN文章定义了 DeepClone( )
函数,并使用了 MemberwiseClone()
。现在,由于这是一个枚举,因此我不需要克隆它,因此我认为 MemberwiseClone()
就足够了。但是,当我在PowerShell中尝试时,克隆的对象似乎只是指向原始对象的指针,而不是克隆对象。我在做什么错?
I have an enumeration, Fruit
, and a class, FruitCollection
, which derives Collection<Fruit>
. I couldn't find a way to clone FruitCollection
using .NET and I found this MSDN article which defined a DeepClone()
function and used MemberwiseClone()
. Now, since this is an enumeration, I don't think I need to "deep" clone it, so I thought MemberwiseClone()
would be sufficient. However, when I try it in PowerShell, the cloned object seems to simply be a pointer to the original object and not a clone. What am I doing wrong?
还有另一种方法可以简单地克隆 Collection
吗? FruitCollection
没有其他自定义成员。
Is there another way to simply clone a Collection
? FruitCollection
has no other custom members.
C#代码:
public enum Fruit
{
Apple = 1,
Orange = 2
}
public class FruitCollection : Collection<Fruit>
{
public FruitCollection Clone()
{
return Clone(this);
}
public static FruitCollection Clone(FruitCollection fruitCollection)
{
return (FruitCollection)fruitCollection.MemberwiseClone();
}
}
PowerShell输出:
PowerShell Output:
PS> $basket1 = New-Object TestLibrary.FruitCollection
PS> $basket1.Add([TestLibrary.Fruit]::Apple)
PS> $basket2 = $basket1.Clone()
PS> $basket1.Add([TestLibrary.Fruit]::Orange)
PS> $basket2
Apple
Orange
推荐答案
正如其他人在评论中指出的那样,您可以使用Collection上已经存在的构造函数,然后在 Clone
中,为要使用的新Collection创建一个新列表,以便
As others have pointed out in the comments, you can use the constructor that already exists on Collection and then in your Clone
, create a new list for the new Collection to use so adding to basket1 doesn't affect basket2 and so forth.
public class FruitCollection : Collection<Fruit>
{
public FruitCollection(IList<Fruit> source) : base(source)
{
}
public FruitCollection()
{
}
public FruitCollection Clone()
{
return Clone(this);
}
public static FruitCollection Clone(FruitCollection fruitCollection)
{
// ToList() will give a new List. Otherwise Collection will use the same IList we passed.
return new FruitCollection(fruitCollection.ToList());
}
}
void Main()
{
var basket1 = new FruitCollection();
basket1.Add(Fruit.Apple);
var basket2 = basket1.Clone();
basket2.Add(Fruit.Orange);
Console.WriteLine("{0}", basket1.Count);
Console.WriteLine("{0}", basket2.Count);
}
这篇关于如何克隆Collection< T> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!