最快的方法做浅复制在C# [英] Fastest Way to do Shallow Copy in C#

查看:155
本文介绍了最快的方法做浅复制在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道什么是做浅复制在C#中最快的方法是什么?我只知道有2个方法可以做到浅拷贝:




  1. MemberwiseClone

  2. 复制每个字段由一个(手动)



  3. 我发现,(2)是速度比(1)。我不知道是否有另一种方式来做到浅拷贝?


    解决方案

    这是有很多可能的解决方案和许多复杂的问题优点和缺点每个。这里有一个精彩的文章 ,概述了在C#中制作副本的几种不同的方式。总结:




    1. 克隆手动结果
      乏味,但控制的高水平


    2. 克隆与MemberwiseClone结果
      只创建一个浅表副本,即对于引用类型字段的原始对象,它的克隆指的是同一个对象。


    3. 在默认情况下反射结果
      浅拷贝克隆,可以重新写入做深拷贝。优点:自动化。缺点:反映很慢


    4. 克隆与序列化的结果
      容易,自动化。放弃一些控制和序列化是最慢的所有。


    5. 克隆与IL,克隆与扩展方法结果
      更先进的解决方案,而不是常见的。



    I wonder what is the fastest way to do shallow copying in C#? I only know there are 2 ways to do shallow copy:

    1. MemberwiseClone
    2. Copy each field one by one (manual)

    I found that (2) is faster than (1). I'm wondering if there's another way to do shallow copying?

    解决方案

    This is a complex subject with lots of possible solutions and many pros and cons to each. There is a wonderful article here that outlines several different ways of making a copy in C#. To summarize:

    1. Clone Manually
      Tedious, but high level of control.

    2. Clone with MemberwiseClone
      Only creates a shallow copy, i.e. for reference-type fields the original object and it's clone refer to the same object.

    3. Clone with Reflection
      Shallow copy by default, can be re-written to do deep copy. Advantage: automated. Disadvantage: reflection is slow.

    4. Clone with Serialization
      Easy, automated. Give up some control and serialization is slowest of all.

    5. Clone with IL, Clone with Extension Methods
      More advanced solutions, not as common.

    这篇关于最快的方法做浅复制在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆