C#数组复制按值 [英] C# Copy Array by Value
问题描述
我有一个类型数组的MyType []类型;
我想使这个数组的独立副本。我想这
I have a typed array MyType[] types;
and i want to make and independant copy of this array. i tried this
MyType[] types2 = new MyType[types.Length] ;
types2 = types ;
但这创建到第一参考。然后,我尝试
but this create a reference to the first. I then tried
Array.Copy( types , types2 , types.Length ) ;
但我有同样的问题:第一个数组中更改值改变了副本中的值以及
but I have the same problem: changing a value in the first array changes the value in the copy as well.
我怎样才能使一个阵列,IList的或IEnumerable的?
How can I make a completely independent or deep copy of an Array, IList or IEnumerable?
推荐答案
实施上的MyType的克隆方法,使用保护方法MemberwiseClone(执行浅拷贝),或者使用了深刻的克隆技术。你可以把它实现为ICloneable然后写几个扩展方法,将克隆corresponsing集合。
Implement a clone method on MyType, using protected method MemberwiseClone (performs shallow copy) or using a deep cloning technique. You can have it implement an ICloneable then write several extensions methods that will clone the corresponsing collection.
interface ICloneable<T>
{
T Clone();
}
public static class Extensions
{
public static T[] Clone<T>(this T[] array) where T : ICloneable<T>
{
var newArray = new T[array.Length];
for (var i = 0; i < array.Length; i++)
newArray[i] = array[i].Clone();
return newArray;
}
public static IEnumerable<T> Clone<T>(this IEnumerable<T> items) where T : ICloneable<T>
{
foreach (var item in items)
yield return item.Clone();
}
}
您必须这样做,因为当您使用Array.Copy它复制引用,没有引用的对象创建一个新的数组。每种类型的负责复制自身。
You must do this because while a new array is created when you use Array.Copy it copies the references, not the objects referenced. Each type is responsible for copying itself.
这篇关于C#数组复制按值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!