我想做一些事情,比如:

MyObject myObj = GetMyObj(); // Create and fill a new object
MyObject newObj = myObj.Clone();

然后对未反映在原始对象中的新对象进行更改。

我通常不需要这个功能,所以当有必要时,我会创建一个新对象,然后单独复制每个属性,但这总是让我觉得有更好或更优雅的方法来处理这种情况。

如何克隆或深度复制对象,以便在原始对象中不反映任何更改的情况下修改克隆的对象?


当前回答

DeepClonner:快速、简单、有效的NuGet包解决克隆问题

看完所有的答案后,我很惊讶没有人提到这个优秀的包:

DeepCloner GitHub项目

DeepCloner NuGet包

详细介绍一下它的README,下面是我们选择它的原因:

它可以深层或浅层复制在深度克隆中,维护所有对象图。在运行时使用代码生成,因为结果克隆非常快由内部结构复制的对象,未调用方法或构造函数您不需要以某种方式标记类(如Serializable属性或实现接口)无需为克隆指定对象类型。对象可以被强制转换为接口或抽象对象(例如,您可以将int数组克隆为抽象array或IEnumerable;甚至可以克隆null而不出错)克隆的对象没有任何能力确定他是克隆的(除非使用非常特定的方法)

用法:

var deepClone = new { Id = 1, Name = "222" }.DeepClone();
var shallowClone = new { Id = 1, Name = "222" }.ShallowClone();

性能:

README包含各种克隆库和方法的性能比较:DeepCloner性能。

要求:

.NET 4.0或更高版本或.NET Standard 1.3(.NET Core)需要完全信任权限集或反射权限(MemberAccess)

其他回答

简单的答案是从ICloneable接口继承,然后实现.clone函数。克隆应该按成员进行复制,并对任何需要它的成员执行深度复制,然后返回结果对象。这是一个递归操作(它要求您要克隆的类的所有成员都是值类型或实现ICloneable,并且它们的成员是值类型或者实现IClonea,依此类推)。

有关使用ICloneable克隆的详细说明,请参阅本文。

长篇大论的答案是“视情况而定”。正如其他人所提到的,ICloneable不受泛型支持,需要对循环类引用进行特殊考虑,并且实际上被一些人视为.NET Framework中的“错误”。序列化方法取决于对象是否可序列化,而这些对象可能不可序列化,并且您可能无法控制。对于哪种做法是“最佳”做法,社会上仍有很多争论。事实上,没有一个解决方案是适用于所有情况的一刀切的最佳实践,就像ICloneable最初被解释的那样。

请参阅本开发者角文章,了解更多选项(归功于Ian)。

遵循以下步骤:

使用返回T的只读Self属性和ICloneable<out T>定义ISelf<T>,ICloneale<out T<派生自ISelf>并包含方法T Clone()。然后定义一个CloneBase类型,该类型实现了一个受保护的虚拟泛型VirtualClone,将MemberwiseClone转换为传入的类型。每个派生类型都应该通过调用基本克隆方法来实现VirtualClone,然后执行所需的操作来正确克隆父VirtualClone方法尚未处理的派生类型的那些方面。

为了实现最大的继承通用性,公开公共克隆功能的类应该是密封的,但派生自一个基类,该基类在其他方面是相同的,除非缺少克隆。不要传递显式可克隆类型的变量,而是采用ICloneable<theNonCloneableType>类型的参数。这将允许期望Foo的可克隆衍生物与DerivedFoo的可克隆衍生物一起工作的例程,但也允许创建Foo的不可克隆衍生物。

DeepClonner:快速、简单、有效的NuGet包解决克隆问题

看完所有的答案后,我很惊讶没有人提到这个优秀的包:

DeepCloner GitHub项目

DeepCloner NuGet包

详细介绍一下它的README,下面是我们选择它的原因:

它可以深层或浅层复制在深度克隆中,维护所有对象图。在运行时使用代码生成,因为结果克隆非常快由内部结构复制的对象,未调用方法或构造函数您不需要以某种方式标记类(如Serializable属性或实现接口)无需为克隆指定对象类型。对象可以被强制转换为接口或抽象对象(例如,您可以将int数组克隆为抽象array或IEnumerable;甚至可以克隆null而不出错)克隆的对象没有任何能力确定他是克隆的(除非使用非常特定的方法)

用法:

var deepClone = new { Id = 1, Name = "222" }.DeepClone();
var shallowClone = new { Id = 1, Name = "222" }.ShallowClone();

性能:

README包含各种克隆库和方法的性能比较:DeepCloner性能。

要求:

.NET 4.0或更高版本或.NET Standard 1.3(.NET Core)需要完全信任权限集或反射权限(MemberAccess)

代码生成器

我们已经看到了很多想法,从序列化到手动实现再到反射,我想使用CGbR代码生成器提出一种完全不同的方法。生成克隆方法具有内存和CPU效率,因此比标准DataContractSerializer快300倍。

你只需要一个带有ICloneable的部分类定义,生成器就可以完成剩下的工作:

public partial class Root : ICloneable
{
    public Root(int number)
    {
        _number = number;
    }
    private int _number;

    public Partial[] Partials { get; set; }

    public IList<ulong> Numbers { get; set; }

    public object Clone()
    {
        return Clone(true);
    }

    private Root()
    {
    }
} 

public partial class Root
{
    public Root Clone(bool deep)
    {
        var copy = new Root();
        // All value types can be simply copied
        copy._number = _number; 
        if (deep)
        {
            // In a deep clone the references are cloned 
            var tempPartials = new Partial[Partials.Length];
            for (var i = 0; i < Partials.Length; i++)
            {
                var value = Partials[i];
                value = value.Clone(true);
                tempPartials[i] = value;
            }
            copy.Partials = tempPartials;
            var tempNumbers = new List<ulong>(Numbers.Count);
            for (var i = 0; i < Numbers.Count; i++)
            {
                var value = Numbers[i];
                tempNumbers.Add(value);
            }
            copy.Numbers = tempNumbers;
        }
        else
        {
            // In a shallow clone only references are copied
            copy.Partials = Partials; 
            copy.Numbers = Numbers; 
        }
        return copy;
    }
}

注意:最新版本有更多的空检查,但为了更好地理解,我省略了它们。

虽然一种方法是实现ICloneable接口(在这里描述,所以我不会反悔),但这里有一个很好的深度克隆对象复制器,我不久前在代码项目中找到了它,并将其合并到我们的代码中。如其他地方所述,它要求您的对象是可序列化的。

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

/// <summary>
/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
/// Provides a method for performing a deep copy of an object.
/// Binary Serialization is used to perform the copy.
/// </summary>
public static class ObjectCopier
{
    /// <summary>
    /// Perform a deep copy of the object via serialization.
    /// </summary>
    /// <typeparam name="T">The type of object being copied.</typeparam>
    /// <param name="source">The object instance to copy.</param>
    /// <returns>A deep copy of the object.</returns>
    public static T Clone<T>(T source)
    {
        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type must be serializable.", nameof(source));
        }

        // Don't serialize a null object, simply return the default for that object
        if (ReferenceEquals(source, null)) return default;

        using var Stream stream = new MemoryStream();
        IFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, source);
        stream.Seek(0, SeekOrigin.Begin);
        return (T)formatter.Deserialize(stream);
    }
}

其思想是它序列化对象,然后将其反序列化为新对象。好处是,当对象变得太复杂时,您不必担心克隆任何东西。

如果您希望使用C#3.0的新扩展方法,请将该方法更改为具有以下签名:

public static T Clone<T>(this T source)
{
   // ...
}

现在,方法调用简单地变成objectBeingCloned.Clone();。

EDIT(2015年1月10日)我想我会重新考虑这个问题,要说我最近开始使用(Newtonsoft)Json来做这个,它应该更轻,并避免[Serializable]标签的开销。(NB@atconway在评论中指出,私有成员不是使用JSON方法克隆的)

/// <summary>
/// Perform a deep Copy of the object, using Json as a serialization method. NOTE: Private members are not cloned using this method.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T CloneJson<T>(this T source)
{            
    // Don't serialize a null object, simply return the default for that object
    if (ReferenceEquals(source, null)) return default;

    // initialize inner objects individually
    // for example in default constructor some list property initialized with some values,
    // but in 'source' these items are cleaned -
    // without ObjectCreationHandling.Replace default constructor values will be added to result
    var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace};

    return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings);
}