zoukankan      html  css  js  c++  java
  • 克隆示例

    值类型使用基于值的语法,结构(也包括所有数值数据类型int,float等,以及任何枚举或自定义结构)。

    如果有一个仅包含值类型的类或结构,使用MemberwiseClone()实现Clone()方法。如果有一个保存其他引用类型的自定义类型,需要建立一个考虑了每个引用类型成员变量的新对象。

     1 // 该类定义了一个点
     2     public class PointDescription
     3     {
     4         public string PetName { get; set; }
     5         public Guid PointID { get; set; }
     6 
     7         public PointDescription()
     8         {
     9             PetName = "No-name";
    10             PointID = Guid.NewGuid();
    11         }
    12     }
     1 public class Point : ICloneable
     2     {
     3         public int X { get; set; }
     4         public int Y { get; set; }
     5         public PointDescription desc = new PointDescription();
     6 
     7         public Point( int xPos, int yPos, string petName )
     8         {
     9             X = xPos; Y = yPos;
    10             desc.PetName = petName;
    11         }
    12         public Point( int xPos, int yPos )
    13         {
    14             X = xPos; Y = yPos;
    15         }
    16         public Point() { }
    17 
    18         // 重写 Object.ToString().
    19         public override string ToString()
    20         {
    21             return string.Format("X = {0}; Y = {1}; Name = {2};
    ID = {3}
    ",
    22             X, Y, desc.PetName, desc.PointID);
    23         }
    24 
    25         // 需要调整 PointDescription成员
    26         public object Clone()
    27         {
    28             // 获取浅复制
    29             Point newPoint = (Point)this.MemberwiseClone();
    30 
    31             // 填充间距
    32             PointDescription currentDesc = new PointDescription();
    33             currentDesc.PetName = this.desc.PetName;
    34             newPoint.desc = currentDesc;
    35             return newPoint;
    36         }
    37     }

    Point p3 = new Point(100, 100, "Jane");
    Point p4 = (Point)p3.Clone();
    这样返回自Clone()的Point复制了它的内部引用类型成员变量,而不是在内存中“指向”同样的对象。

  • 相关阅读:
    drf3
    字典的操作方法
    列表的操作方法
    字符串的操作方法
    while循环和基本运算符
    初识数据类型
    USDT相关
    带团队
    CentOS7更改时区及同步网络时间
    mac胡刷新dns
  • 原文地址:https://www.cnblogs.com/ht-beyond/p/4470486.html
Copyright © 2011-2022 走看看