中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

c#實(shí)現(xiàn)深拷貝代碼

2018-07-20    來(lái)源:open-open

容器云強(qiáng)勢(shì)上線!快速搭建集群,上萬(wàn)Linux鏡像隨意使用

淺拷貝是指源對(duì)象與拷貝對(duì)象共用一份實(shí)體,僅僅是引用的變量不同(名稱不同)。對(duì)其中任何一個(gè)對(duì)象的改動(dòng)都會(huì)影響另外一個(gè)對(duì)象。舉個(gè)例子,一個(gè)人一開(kāi)始叫張三,后來(lái)改名叫李四了,可是還是同一個(gè)人,不管是張三缺胳膊少腿還是李四缺胳膊少腿,都是這個(gè)人倒霉。

深拷貝是指源對(duì)象與拷貝對(duì)象互相獨(dú)立,其中任何一個(gè)對(duì)象的改動(dòng)都不會(huì)對(duì)另外一個(gè)對(duì)象造成影響。舉個(gè)例子,一個(gè)人名叫張三,后來(lái)用他克隆(假設(shè)法律允許)了另外一個(gè)人,叫李四,不管是張三缺胳膊少腿還是李四缺胳膊少腿都不會(huì)影響另外一個(gè)人。比較典型的就是Value(值)對(duì)象,如預(yù)定義類型Int32,Double,以及結(jié)構(gòu)(struct),枚舉(Enum)等。

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>(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);
        }
    }
}

標(biāo)簽:

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請(qǐng)聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請(qǐng)與原作者聯(lián)系。

上一篇:利用Gson實(shí)現(xiàn)Json串和Java Bean互轉(zhuǎn)

下一篇:使用zip4j加密和解密文件和目錄