Deep Copy in C#

后端 未结 8 742
独厮守ぢ
独厮守ぢ 2021-02-05 20:36

MSDN gives this example of a deep copy (http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx)

public class Person 
{
    public int Age;
           


        
8条回答
  •  半阙折子戏
    2021-02-05 21:10

    Alternatively, if you are able to set Serializable attribute to all involved classes, you can use serialization. For the purpose of a generic deep copy I have this object extension method:

    public static class ObjectExtensions
    {
        #region Methods
    
        public static T Copy(this T source)
        {
            var isNotSerializable = !typeof(T).IsSerializable;
            if (isNotSerializable)
                throw new ArgumentException("The type must be serializable.", "source");
    
            var sourceIsNull = ReferenceEquals(source, null);
            if (sourceIsNull)
                return default(T);
    
            var formatter = new BinaryFormatter();
            using (var stream = new MemoryStream())
            {
                formatter.Serialize(stream, source);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(stream);
            }
        }
    
        #endregion
    }
    

    This should also copy your IdInfo field.

    Usage is simple:

    var copy = obj.Copy();
    

提交回复
热议问题