c# clone Class one:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { DemoClass demoClass = new DemoClass(); demoClass.DemoFiled = 2; var clone = (DemoClass)demoClass.Clone(); Console.WriteLine(demoClass.DemoFiled); Console.WriteLine(clone.DemoFiled); Console.ReadKey(true); } } class DemoClass : ICloneable { #region << Field >> public int DemoFiled { get; set; } #endregion #region << Method >> public object Clone() { DemoClass demoClass = new DemoClass(); demoClass.DemoFiled = this.DemoFiled; return demoClass; } #endregion } }
上面的代码就是简单的实现ICloneable借口。对于简单的类,这种实现没什么麻烦,当类复杂的时候,那就是悲剧。
Two:
通过序列化来Clone Class
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { DemoClass demoClass = new DemoClass(); demoClass.DemoFiled = 2; var clone = DemoUtil.ObjectClone<DemoClass>(demoClass); Console.WriteLine(demoClass.DemoFiled); Console.WriteLine(clone.DemoFiled); Console.ReadKey(true); } } [Serializable] class DemoClass { #region << Field >> public int DemoFiled { get; set; } #endregion } public static class DemoUtil { #region << Method >> public static T ObjectClone<T>(T obj) { var type = typeof(T); if (!type.IsSerializable) return default(T); if (Object.ReferenceEquals(obj, null)) return default(T); IFormatter format = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { try { format.Serialize(ms, obj); ms.Seek(0, SeekOrigin.Begin); return (T)format.Deserialize(ms); } catch (Exception e) { return default(T); } } } #endregion } }
我个人认为序列化是比较好Deep copy,并且可以控制序列化的范围。(大部分人又会说性能问题,和反射一样,其实这点性能对于不是大数据的处理,完全不是问题,如果要处理
大数据,建议直接用C编写处理代码,dll来调用)
three:
就是反射了。一说反射。哎,不论好坏,就开始喷性能。(TT)
对于大数据确实不行,但不是每款软件都是大数据的。
推荐国外的反射,写的确实惊艳。
codeproject 搜索 C# object Cloning Machinery
连接不会贴。。