深克隆C#代码

软件测试工程师最常用的Linux系统命令大全(汇总) cd命令这是一个非常基本,也是大家经常需要使用的命令,它用于切换当前目录,它的参数是要切换到的目录的路径,可以是绝对路径,也可以是相对路径。 阅读详情
 看了http://www.codeproject.com/KB/cs/cloneimpl_class.aspx的文章,他的代码确实不错,稍做修改贴在这里。
href="file:///D:/temp/msohtmlclip1/01/clip_filelist.xml" rel="File-List" /> href="file:///D:/temp/msohtmlclip1/01/clip_themedata.thmx" rel="themeData" /> href="file:///D:/temp/msohtmlclip1/01/clip_colorschememapping.xml" rel="colorSchemeMapping" />

using System;

using System.Collections.Generic;

using System.Text;

using System.Reflection;

using System.Collections;

 

namespace CloneTest

{

    public class Clone

    {

    }

 

    public class MyClass : BaseObject

    {

        public string myStr ="test";

        public int id;

    }

 

    public class MyContainer : BaseObject

    {

        public string name = "test2";

        public MyClass[] myArray= new MyClass[5];

 

        public MyContainer()

        {

            for(int i=0 ; i< 5 ; i++)

            {

                 this.myArray[i] = new MyClass();

            }

        }

    }

 

    /// <summary>

 

    /// BaseObject class is an abstract class for you to derive from.

 

    /// Every class that will be dirived from this class will support the

 

    /// Clone method automaticly.

 

 

    /// The class implements the interface ICloneable and there

 

    /// for every object that will be derived

 

 

    /// from this object will support the ICloneable interface as well.

 

    /// </summary>

 

 

    public abstract class BaseObject : ICloneable

    {

        /// <summary>

 

        /// Clone the object, and returning a reference to a cloned object.

 

        /// </summary>

 

        /// <returns>Reference to the new cloned

 

        /// object.</returns>

 

        public object Clone()

        {

            //First we create an instance of this specific type.

 

            object newObject  = Activator.CreateInstance( this.GetType() );

 

            //We get the array of fields for the new type instance.

 

            FieldInfo[] fields = newObject.GetType().GetFields();

 

            int i = 0;

 

            foreach( FieldInfo fi in this.GetType().GetFields() )

            {

                //We query if the fiels support the ICloneable interface.

 

                Type ICloneType = fi.FieldType.

                            GetInterface( "ICloneable" , true );

 

                if( ICloneType != null )

                {

                    //Getting the ICloneable interface from the object.

 

                    ICloneable IClone = (ICloneable)fi.GetValue(this);

 

                    //We use the clone method to set the new value to the field.

 

                    fields[i].SetValue( newObject , IClone.Clone() );

                }

                else

                {

                    // If the field doesn't support the ICloneable

 

                    // interface then just set it.

 

                    fields[i].SetValue( newObject , fi.GetValue(this) );

                }

 

                //Now we check if the object support the

 

                //IEnumerable interface, so if it does

 

                //we need to enumerate all its items and check if

 

                //they support the ICloneable interface.

 

                Type IEnumerableType = fi.FieldType.GetInterface

                                ( "IEnumerable" , true );

                if( IEnumerableType != null )

                {

                    //Get the IEnumerable interface from the field.

 

                    IEnumerable IEnum = (IEnumerable)fi.GetValue(this);

 

                    //This version support the IList and the

 

                    //IDictionary interfaces to iterate on collections.

 

                    Type IListType = fields[i].FieldType.GetInterface

                                        ( "IList" , true );

                    Type IDicType = fields[i].FieldType.GetInterface

                                        ( "IDictionary" , true );

 

                    int j = 0;

                    if( IListType != null )

                    {

                        //Getting the IList interface.

 

                        IList list = (IList)fields[i].GetValue(newObject);

 

                        foreach( object obj in IEnum )

                        {

                            //Checking to see if the current item

 

                            //support the ICloneable interface.

 

                            ICloneType = obj.GetType().

                                GetInterface( "ICloneable" , true );

                           

                            if( ICloneType != null )

                            {

                                //If it does support the ICloneable interface,

 

                                //we use it to set the clone of

 

                                //the object in the list.

 

                                ICloneable clone = (ICloneable)obj;

 

                                list[j] = clone.Clone();

                            }

 

                            //NOTE: If the item in the list is not

 

                            //support the ICloneable interface then in the

 

                            //cloned list this item will be the same

 

                            //item as in the original list

 

                            //(as long as this type is a reference type).

 

 

                            j++;

                        }

                    }

                    else if( IDicType != null )

                    {

                        //Getting the dictionary interface.

 

                        IDictionary dic = (IDictionary)fields[i].

                                            GetValue(newObject);

                        j = 0;

                       

                        foreach( DictionaryEntry de in IEnum )

                        {

                            //Checking to see if the item

 

                            //support the ICloneable interface.

 

                            ICloneType = de.Value.GetType().

                                GetInterface( "ICloneable" , true );

 

                            if( ICloneType != null )

                            {

                                ICloneable clone = (ICloneable)de.Value;

 

                                dic[de.Key] = clone.Clone();

                            }

                            j++;

                        }

                    }

                }

                i++;

            }

            return newObject;

        }

    }

}

 

Onnxruntime之YOLOP部署过程记录 魔改YoloP部署过程记录 阅读详情

相关推荐

Vmware 17保姆级教程:从零部署华为enspPro模拟器(附镜像下载+配置优化)

本文提供了一份详尽的Vmware 17部署华为eNSP Pro模拟器的保姆级教程。内容涵盖从镜像下载、虚拟机导入、网络配置到深度性能调优的全过程,并针对常见启动失败、设备卡顿等故障提供了实用的排查方案,旨在帮助网络工程师和华为认证备考者快速搭建稳定高效的实验环境。

arduino9maker的博客 636

C#中的深复制和浅复制(在C#中克隆对象) 整理

http://www.codeproject.com/KB/cs/cloneimpl_class.aspxDownload source files - 1.27 KbIntroductionAlthough the subject of cloning in the real world is controversial, in the .NET world it is still safe t

蓝叶菱的专栏 861

腾讯WeKnora开源了!手把手教你用Docker+Ollama本地部署多模态知识库(附避坑指南)

本文详细介绍了腾讯开源的多模态知识库工具WeKnora的本地部署方法,通过Docker和Ollama实现完全离线运行。文章包含环境准备、核心组件配置、Ollama模型集成、系统启动验证及高级性能调优等实战内容,特别适合需要构建私有化知识库的中小团队和个人开发者。

weixin_30664051的博客 479

浅克隆和深克隆的区别与实现

什么是克隆 克隆就是依据已经有的数据,创造一份新的完全一样的数据拷贝。 实现克隆有多种方式,可以手工的new出一个新的对象,然后将原来的对象信息一个一个的set到新的对象中。还有就是使用clone方法。使用clone方法必须满足: 对象的类实现Cloneable接口; 覆盖Object类的clone()方法 (覆盖clone()方法,访问修饰符设为public,默认是protected);...

JinXYan的博客 5234

逆向分析第一步:如何从HEX文件‘还原’出单片机的原始程序与数据?

本文详细解析了如何从HEX文件逆向分析出单片机的原始程序与数据,涵盖了固件逆向的底层逻辑与实践。通过介绍HEX文件的结构、内存映像重建技术以及专业工具链的使用,帮助读者掌握从十六进制数据到可执行代码的完整流程,适用于嵌入式系统开发和逆向工程领域。

weixin_29745609的博客 317

Cadence ADE实战:1GHz VCO相位噪声仿真全流程(附PSS/Pnoise避坑指南)

本文详细介绍了在Cadence ADE环境中对1GHz VCO进行相位噪声仿真的完整流程。重点剖析了PSS(周期性稳态分析)和Pnoise(周期性噪声分析)两大核心引擎的关键参数设置与避坑指南,帮助射频与模拟IC设计者准确评估VCO性能,解决仿真不收敛、结果异常等常见问题。

rock5的博客 671

【转】C#浅度克隆和深度克隆

原文链接:https://blog.youkuaiyun.com/ni_zhi/article/details/5764694 C#复制有深度复制和浅度复制,与赋值运算(=)进行复制的比较。 首先,定义一个类Content作为后面要用的字段类型,Content包含一个int型字段Val。 public class Content { public int Val; } 然后...

烟花易冷 638

【5G演进】4G到5G演进之网络架构与协议栈

4G到5G演进之网络架构与协议栈

Learning makes me happy (0^◇^0) 5531

C# 克隆对象快捷方法

经常做UI的同学应该知道, 常常会遇到某项编辑,编辑后可以保存跟不保存。 这个时候你就需要把当前对象clone 一份出来编辑才可以。 其实object对象自己有clone的方法:MemberwiseClone() 方法,创建当前 object 的浅表副本。 但是因为是浅表副本,所以里面的引用类型是无法复制。当然,可以考虑用结构struc它操作,如果数据量大可能会影响效率,解决方法

祯吒 823

基于STM32L4XX的环境光传感器(VCNL4040M3OE)应用程序设计

• 集成模块:红外发射器(IRED)、环境光传感器(ALS)、接近传感器(PS)及信号调理IC。#define VCNL4040_I2C_ADDR (0x60 << 1) // 7位地址左移一位。// 组合成16位值。// I2C总线句柄。// 设置参数:ALS集成时间160ms,中断禁止,ALS功能开启。// 设置参数:PS工作频率80Hz,开红外二极管,PS功能开启。// 初始化I2C外设。• 输出类型:I2C总线(ALS/PS)// 2. 配置环境光传感器 (ALS) 并启动。

myron6688的博客 143

视频理解与处理——OpenClaw视频能力深度解析(2026视频版)

本文介绍了OpenClaw视频理解与处理的核心技术,重点分析了视频预处理流程。通过VideoProcessor类实现视频加载、帧采样、尺寸调整和归一化等基础处理功能,支持本地和在线视频源处理,为后续视频分析任务提供标准化输入。预处理模块采用均匀采样和标准化方法优化视频数据,确保动作识别、场景分析等高级应用的准确性,展现了OpenClaw强大的视频处理能力。

一键难忘的博客 464

C#复制可序列化的对象的泛型方法

public static class ObjectCopier { public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { ...

qq_41661046的博客 407

thinkphp6/8 - 实现评论区发表评论、回复评论功能数据库表设计与整个逻辑思路过程分析,tp5 评论盖楼等功能(附带源码稍加改造即可使用)

tp5评论区数据库表设计,tp5发表回复评论功能设计,thinkphp5如何做评论功能,tp5 php评论区实现发表回复删除评论,tp5评论区盖楼源码及数据表设计思路,thinkphp评论功能详细教程,thinkphp实现评论与回复功能,thinkphp实现文章评论和回复评论功能,tp5实现评论回复功能,thinkphp如何实现评论区,tp5网站PC移动端h5怎么做评论区发表留言及回复功能,thinkphp实现评论区插件,thinkphp评论区相互发表回复功能详细教程,thinkphp有没有评论区的组件插件

✅ 精选推荐文章 3159

小技巧:利用 MemberwiseClone() 简化 C# 中 Clone() 深克隆代码

前言 在单例模式的应用场景中,Clone() 方法会大量使用,我们在写代码的时候经常会写很多的代码,用于字段或属性的复制,这样的操作不仅麻烦,而且在变更时也不易于修改。实际上我们有更简单的方法,现在就以一个实例来解释这个技巧。 示例 class Student { public int ID {get; set;} = 0; public string Name {get; set...

郝伟老师的博客——大数据、并行计算与人工智能时代 3722

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

C# 使用Emit深克隆

C# 使用Emit深克隆 原文:C# 使用Emit深克隆 有人问,复制一个类所有属性到另一个类有多少方法?这也就是问深克隆有多少个方法,容易想的有三个。直接复制,反射复制,序列化复制。但是性能比较快的有表达式树复制 IL复制两个,本文主要讲最后一个 关于表达式树复制,参见 Fast Deep Copy by Ex...

weixin_30367543的博客 121

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

使用c#强大的表达式树实现对象的深克隆

var a = new TestDto() { Id = 1, Name = "小明", Child = new TestDto() { Id = 2, Name = "小红" }, Record = new Dictionary() { { "1年级", 1 }, { "2年级", 2 } }, Scores = [100, 95] };总之,C# 的表达式树提供了一个强大的机制,可以将代码以数据结构的形式表示出来,使得代码可以在运行时进行检查、修改或执行。

Gefangenes的博客 1190

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

c#基础工具—对象克隆ObjectCloneUtils

一、情景分析 对象克隆对程序开发来说是一个很常见的小需求,就c#而言实现也很简单,浅克隆的的话使用MemberwiseClone,深克隆的话使用一种序列化方式,然后在反序列化就可以了。这篇文章提供的代码,不涉及到高深的技术,如果有什么亮点的话,可能就是通用话强点。 二、代码设计要求 1、要实现两个方法:浅克隆Clone和深DeepClone 2、要做到比较通用,支持泛型。使用方便,一遍需求不用增加代码 3、根据约定优于配置的原则,在设计中减少接口和配置文件的约束。但要能灵活的控制...

小红楼 1585

C#之Clone

因为类的实例是引用类型,要想用原有的类中的实例的数据的话,既要想创建原对象的一个副本的话,只能用clone方法。Clone方法分为深clone和浅clone在C#中提供了浅clone的方法,即为MemberwiseClone() class Program { static void Main(string[] args) { ...

260

C# 浅克隆与深克隆 父子类转

一、浅克隆: 在浅克隆中,如果原型对象的成员变量是值类型,将复制一份给克隆对象;如果原型对象的成员变量是引用类型,则将引用对象的地址复制一份给克隆对象,也就是说原型对象和克隆对象的成员变量指向相同的内存地址。简单来说,在浅克隆中,当对象被复制时只复制它本身和其中包含的值类型的成员变量,而引用类型的成员对象并没有复制,如图: 在C#中,通过实现ICloneable接口的Clone方法(...

无名大白 484

C#中的对象深克隆使用

小禾斗专栏 1878

C# 浅克隆与深克隆

一、浅克隆:      在浅克隆中,如果原型对象的成员变量是值类型,将复制一份给克隆对象;如果原型对象的成员变量是引用类型,则将引用对象的地址复制一份给克隆对象,也就是说原型对象和克隆对象的成员变量指向相同的内存地址。简单来说,在浅克隆中,当对象被复制时只复制它本身和其中包含的值类型的成员变量,而引用类型的成员对象并没有复制,如图: 在C#中,通过实现ICloneable接口的Clone方

zhulongxi的博客 1万+

原型模式(浅克隆和深克隆)

原型模式是一种创建型设计模式,它通过复制一个已经存在的实例来返回新的实例,而不是新建实例.被复制的实例就是我们所称的原型,这个原型是可定制的.原型模式多用于创建复杂的或者耗时的实例, 因为这种情况下,复制一个已经存在的实例可以使程序运行更高效,或者创建值相等,只是命名不一样的同类数据. 原型模式中的拷贝分为"浅拷贝"和"深拷贝":浅克隆: 对值类型的成员变量进行值的复制,对引用类型的成...

211

C# 克隆

一、浅克隆:      在浅克隆中,如果原型对象的成员变量是值类型,将复制一份给克隆对象;如果原型对象的成员变量是引用类型,则将引用对象的地址复制一份给克隆对象,也就是说原型对象和克隆对象的成员变量指向相同的内存地址。简单来说,在浅克隆中,当对象被复制时只复制它本身和其中包含的值类型的成员变量,而引用类型的成员对象并没有复制,如图:   在C#中,通过实现ICloneable接口的Clone...

qq_23018459的博客 325

C#如何深度克隆对象

话不多说上代码: /// <summary> /// 利用序列化进行对象拷贝,要求对象是序列化的 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="item">源对象</param> /// <returns>克隆对象</returns> public T Clone<T>(T item) where T

qq_41946341的博客 1431

C#设计模式之原型(ProtoType)

1.  为什么要用原型?用原型的好处 比如我们有一个工具栏按钮,新建按钮,它是ToolbarButton的实例,它有长度、宽度属性等,而且属性都赋了值。 现在我们要再添加一个保存按钮,它也是ToolbarButton的实例,它也有长度、宽度属性等,不过它还没赋值,它的值和新建按钮的值一样。 如果我们不用原型设计模式的话,可能重新赋一遍值。如果我们用原型设计模式的话,我们可以把新建按钮作为保存...

weixin_34014555的博客 98

c#设计模式5——创建型模式_原型模式

浅克隆 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _1.创建者模式_原型模式//浅克隆 { //用一个已经创建的实例作为原型,通过对原型对象复制,产生一个和原型相同或相似的新对象。 //关注的是大量相同或相似对象的创建问题。 //1、抽象原型类(Prototype):声明一个

mlxg99999的博客 187
上一篇: “开放-封闭”原则--OOD的基石
下一篇: 浅谈SQL Server数据类型最大值
comeon_data
博客等级 码龄22年 15粉丝 63原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值