任意对象拷贝 ObjectCopier

Babybus-u3d技术交流-任意对象拷贝 ObjectCopier

     

 

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.

    /// </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 Clone<T>(this T source)

    {

        if (!typeof(T).IsSerializable)

        {

            throw new ArgumentException("The type must be serializable.", "source");

        }

 
        // Don't serialize a null object, simply return the default for that object

        if (Object.ReferenceEquals(source, null))

        {

            return default(T);

        }

 
        IFormatter formatter = new BinaryFormatter();

        Stream stream = new MemoryStream();

        using (stream)

        {

            formatter.Serialize(stream, source);

            stream.Seek(0, SeekOrigin.Begin);

            return (T)formatter.Deserialize(stream);
        }

    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容