C# 按值复制数组 [英] C# Copy Array by Value

查看:27
本文介绍了C# 按值复制数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型化数组 MyType[] types;我想制作这个数组的独立副本.我试过这个

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.

如何制作 Array、IList 或 IEnumerable 的完全独立或深层副本?

How can I make a completely independent or deep copy of an Array, IList or IEnumerable?

推荐答案

在 MyType 上实现一个克隆方法,使用受保护的方法 MemberwiseClone(执行浅拷贝)或使用深克隆技术.您可以让它实现一个 ICloneable,然后编写几个扩展方法来克隆相应的集合.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆