zoukankan      html  css  js  c++  java
  • C#之Clone

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

     class Program
        {
            static void Main(string[] args)
            {
                Person p = new Person() { Age=12, Name="张三" };
                Person p2 = (Person)p.Clone();
                p2.Name = "李四";
                Console.WriteLine("p.Name="+ p.Name);
                Console.WriteLine("p2.Name=" + p2.Name);
                Console.ReadKey();
    
            }
        }
        public class Person:System.ICloneable
        {
            public string Name { get; set; }
            public int Age { get; set; }
    
            public object Clone()
            {
                return this.MemberwiseClone();
            }
        }

    输出结果: 

    MemberwiseClone()方法执行的只是浅层拷贝。而深层拷贝要递归的拷贝其字段所引用的所有对象。 

    深克隆:即,要在它的每一个包含的类中实现浅Clone

    public class DeepClone : System.ICloneable
        {
            Person g;
            Person b;
            public Object Clone()
            {
                DeepClone dc = (DeepClone)this.MemberwiseClone();
                dc.g = (Person)(this.g.Clone());
                dc.b = (Person)(this.b.Clone());
                return dc;
            }
        }
  • 相关阅读:
    freemaker获取字符串长度
    freemarker截取字符串subString
    [转]freemarker中的list
    python常用模块——os模块
    python正则表达式
    需要区分对比的函数以及函数小结
    信道极限容量
    信道和调制
    python中颜色设置
    python中的exec()、eval()以及complie()
  • 原文地址:https://www.cnblogs.com/xbblogs/p/5663827.html
Copyright © 2011-2022 走看看