C# 按值复制数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1215198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Copy Array by Value
提问by JOBG
I have a typed array MyType[] types;
and i want to make and independant copy of this array. i tried this
我有一个类型化的数组MyType[] types;
,我想制作这个数组的独立副本。我试过这个
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.
但我有同样的问题:更改第一个数组中的值也会更改副本中的值。
How can I make a completely independent or deep copy of an Array, IList or IEnumerable?
如何制作 Array、IList 或 IEnumerable 的完全独立或深层副本?
采纳答案by eulerfx
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.
在 MyType 上实现克隆方法,使用受保护的方法 MemberwiseClone(执行浅复制)或使用深度克隆技术。你可以让它实现一个 ICloneable 然后编写几个扩展方法来克隆相应的集合。
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();
}
}
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.
您必须这样做,因为当您使用 Array.Copy 创建一个新数组时,它会复制引用,而不是引用的对象。每种类型都负责复制自身。
回答by Sam Harwell
Based on the first post, all he needs is this for "an independent copy of the array". Changes to the shallowCopy
array itself would not appear in the types
array (meaning element assignment, which really is what he showed above despite saying "deep copy"). If this suits your needs, it will have the best performance.
根据第一篇文章,他所需要的只是“数组的独立副本”。对shallowCopy
数组本身的更改不会出现在types
数组中(意思是元素分配,尽管他说的是“深度复制”,但这确实是上面显示的内容)。如果这符合您的需求,它将具有最佳性能。
MyType[] shallowCopy = (MyType[])types.Clone();
He also mentions a "deep copy" which would be different for mutable types that are not recursive value-type aggregates of primitives. If the MyType
implements ICloneable
, this works great for a deep copy:
他还提到了一个“深拷贝”,这对于不是递归值类型原语聚合的可变类型来说是不同的。如果是MyType
implements ICloneable
,这对于深拷贝非常有效:
MyType[] deepCopy = (MyType[])Array.ConvertAll(element => (MyType)element.Clone());
回答by Fredrik M?rk
If your type is serializable you can use serialization techniques to get a copy of your array (including deep copies of the items):
如果您的类型是可序列化的,您可以使用序列化技术来获取数组的副本(包括项目的深层副本):
private static object GetCopy(object input)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, input);
stream.Position = 0;
return formatter.Deserialize(stream);
}
}
To use it:
要使用它:
MyType[] items = new MyType[2];
// populate the items in the array
MyType[] copies = (MyType[])GetCopy(items);
回答by Ryan Novack
I wanted to do the same thing: make a copy of an array by value for things like sorting so that I could later reinitialize another temp array with the original source array. After researching this, I found this cannot be done so simply. So, I made a workaround. I will use my own code below:
我想做同样的事情:为排序之类的事情按值制作一个数组的副本,以便我以后可以使用原始源数组重新初始化另一个临时数组。经过研究,我发现这不能这么简单。所以,我做了一个解决方法。我将在下面使用我自己的代码:
string[] planetNames = new string[] { "earth", "venus", "mars" };
string[] tempNames = new string[planetNames.Length];
for (int i = 0; i < planetNames.Length; i++)
{
tempNames[i] = planetNames[i];
}
planetNamesis my source array. tempNamesis the array which I will later sort independently of planetNames. I have tested this and this code does not sort planetNameswhen I sort tempNameswhich is what I was attempting to achieve.
PlanetNames是我的源数组。 tempNames是我稍后将独立于planetNames 排序的数组。我已经对此进行了测试,当我对tempNames进行排序时,此代码不会对PlanetNames进行排序,这正是我试图实现的目标。
回答by Flak714
I've found if you just want a simple char array copy you can trick C# into doing a copy by value using the char:
我发现如果你只想要一个简单的 char 数组副本,你可以欺骗 C# 使用 char 按值进行复制:
char[] newchararray = new char[desiredchararray.Length];
for (int k = 0; k < desiredchararray.Length; k++)
{
char thecharacter = newchararray[k];
newchararray[k] = thecharacter;
oldchararray[k] = oldchararray[k] + 1;
}
Seems to work for me but if anyone disagrees please let me know :)
似乎对我有用,但如果有人不同意,请告诉我:)
回答by heltonbiker
For the impatient:
对于不耐烦的人:
newarray = new List<T>(oldarray).ToArray();
回答by renadeen
If you want to create a copy of just an array with references to objects in old array (or if you have array of value type objects), simplest solution is
如果您只想创建一个数组的副本,并引用旧数组中的对象(或者如果您有值类型对象的数组),最简单的解决方案是
var newArray = oldArray.ToArray()
If you want deep copy you should have a method which copies single object of your type (e.g. public MyType Copy(MyType obj)
). Then solution will look like
如果你想要深度复制,你应该有一个方法来复制你类型的单个对象(例如public MyType Copy(MyType obj)
)。然后解决方案看起来像
var newArray = oldArray.Select(x => Copy(x)).ToArray()