构建可克隆的对象(ICloneable)
ICloneable接口
如果想使自己的自定义类型支持向调用方返回自身同样副本的能力,需要实现标准ICloneable接口。
namespace System
{ public interface ICloneable
{
object Clone();
}
}
浅拷贝
System.Object定义了一个名为MemberwiseClone()的成员。这个方法用来获取当前对象的一份浅拷贝。
例:
Point.cs
namespace CloneablePoint
{
// The Point now supports "clone-ability."
public class Point : ICloneable
{
public int X { get; set; }
public int Y { get; set; }
public PointDescription desc = new PointDescription(); public Point( int xPos, int yPos, string petName )
{
X = xPos; Y = yPos;
desc.PetName = petName;
}
public Point( int xPos, int yPos )
{
X = xPos; Y = yPos;
}
public Point() { } // Override Object.ToString().
public override string ToString()
{
return string.Format("X = {0}; Y = {1}; Name = {2};\nID = {3}\n",
X, Y, desc.PetName, desc.PointID);
} // Return a copy of the current object.
// Now we need to adjust for the PointDescription member.
public object Clone()
{
// 这个复制每个Ponit字段成员
Point newPoint = (Point)this.MemberwiseClone();
return newPoint;
}
}
}
PointDescription.cs
namespace CloneablePoint
{
// This class describes a point.
public class PointDescription
{
public string PetName { get; set; }
public Guid PointID { get; set; } public PointDescription()
{
PetName = "No-name";
PointID = Guid.NewGuid();
}
}
}
Program.cs
namespace CloneablePoint
{
class Program
{
static void Main( string[] args )
{
Console.WriteLine("***** Fun with Object Cloning *****\n");
Console.WriteLine("Cloned p3 and stored new Point in p4");
Point p3 = new Point(, , "Jane");
Point p4 = (Point)p3.Clone(); Console.WriteLine("Before modification:");
Console.WriteLine("p3: {0}", p3);
Console.WriteLine("p4: {0}", p4);
p4.desc.PetName = "My new Point";
p4.X = ; Console.WriteLine("\nChanged p4.desc.petName and p4.X");
Console.WriteLine("After modification:");
Console.WriteLine("p3: {0}", p3);
Console.WriteLine("p4: {0}", p4);
Console.ReadLine();
}
}
}
请注意,如果Ponint包含任何引用类型成员变量,MemberwiseClone()将这些引用复制到对象中(即浅复制)。如果想要支持真正的深复制,需要在克隆过程中创建任何引用类型变量的新实力。
深拷贝
Point.cs
namespace CloneablePoint
{
public class Point : ICloneable
{
public int X { get; set; }
public int Y { get; set; }
public PointDescription desc = new PointDescription(); public Point( int xPos, int yPos, string petName )
{
X = xPos; Y = yPos;
desc.PetName = petName;
}
public Point( int xPos, int yPos )
{
X = xPos; Y = yPos;
}
public Point() { } public override string ToString()
{
return string.Format("X = {0}; Y = {1}; Name = {2};\nID = {3}\n",
X, Y, desc.PetName, desc.PointID);
} public object Clone()
{
Point newPoint = (Point)this.MemberwiseClone(); PointDescription currentDesc = new PointDescription();
currentDesc.PetName = this.desc.PetName;
newPoint.desc = currentDesc;
return newPoint;
}
}
}
PointDescription.cs
namespace CloneablePoint
{
public class PointDescription
{
public string PetName { get; set; }
public Guid PointID { get; set; } public PointDescription()
{
PetName = "No-name";
PointID = Guid.NewGuid();
}
}
}
Program.cs
namespace CloneablePoint
{
class Program
{
static void Main( string[] args )
{
Console.WriteLine("***** Fun with Object Cloning *****\n");
Console.WriteLine("Cloned p3 and stored new Point in p4");
Point p3 = new Point(, , "Jane");
Point p4 = (Point)p3.Clone(); Console.WriteLine("Before modification:");
Console.WriteLine("p3: {0}", p3);
Console.WriteLine("p4: {0}", p4);
p4.desc.PetName = "My new Point";
p4.X = ; Console.WriteLine("\nChanged p4.desc.petName and p4.X");
Console.WriteLine("After modification:");
Console.WriteLine("p3: {0}", p3);
Console.WriteLine("p4: {0}", p4);
Console.ReadLine();
}
}
}
构建可克隆的对象(ICloneable)的更多相关文章
- ES5-ES6-ES7_字符串与JOSN格式的数据相互转换以及深度克隆新对象
这篇文章主要来讲HTML5中的新方法:parse()把字符串转换成josn格式的数据和stringify()把josn格式的数据转换成字符串 eval()方法的回顾 eval()方法可以将任何字符串解 ...
- JavaScript面向对象编程(10)高速构建继承关系之对象拷贝
前面的样例我们是通过构造器创建对象.而且希望该对象继承来自另外一个构造器的对象 我们也能够直接面向一个对象来达成继承的目的.使用下属步骤: 1.拷贝一个对象 2.给新对象加入属性 /** * 通过拷贝 ...
- 利用BeanUtils.copyProperties 克隆出新对象,避免对象重复问题
1.经常用jQuery获取标签里面值val(),或者html(),text()等等,有次想把获取标签的全部html元素包括自己也用来操作,查询了半天发现$("#lefttr1"). ...
- XAF ORMDataModel构建的基础资料对象无法被调用显示的解决办法
修正,其实只要在基础资料类中加入[XafDefaultProperty("名称")]标签即可. namespace NEO.ERP.Module.BusinessObjects.B ...
- ES6 克隆对象 浅克隆:只能克隆原始对象自身的值,不能克隆它继承的值
https://www.cnblogs.com/xbblogs/p/8954165.html return JSON.parse(JSON.stringify(origin)) 最早由Barbara ...
- 深度克隆(对象、数组)--------百度IFE前端task2
var srcObj = { a: 1, b: { b1: ["hello", "hi"], b2: "JavaScript" }}; co ...
- 在JAVASCRIPT中构建一个复杂的对象,并用JSON进行转换
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 精通C#(第6版)
<精通C#(第6版)> 基本信息 原书名:Pro C# 5.0 and the .NET 4.5 framework,sixth edition 作者: (美)Andrew Troelse ...
- .NET 接口
接口 接口是一组抽象成员的集合,表示某个类或结构可以选择去实现的行为,描述的是可属于任何类或结构的一组相关功能.接口方法的实现是在实现接口的类中完成的,实现接口的类可以显式实现该接口的成员, ...
随机推荐
- applicationDefaultJvmArgs:
server.context-path=/HelloMultiServlet server.port=8080 applicationDefaultJvmArgs: [ "-agentlib ...
- mysql 区间锁 对于没有索引 非唯一索引 唯一索引 各种情况
The locks are normally next-key locks that also block inserts into the "gap" immediately b ...
- sed 变量替换 把m.txt文件中的$i替换成$j
zabbix:/root/zabbix# cat a1.sh for j in {1..48} do sed "s/\$i/$j/g" m.txt >>tmp.txt ...
- 【HDOJ】3033 I love sneakers!
分组背包. #include <stdio.h> #include <string.h> #define mymax(a, b) (a>b) ? a:b typedef ...
- Android Volley - volley StringRequest編碼問題
有些時候這個類並不能很好的解決中文編碼問題 如果出現亂碼,就 要重寫該類的parseNetworkResponse 方法了. 繼承StringRequest,然後重寫parseNetworkRespo ...
- (转载)mysql decimal、numeric数据类型
(转载)http://www.cnblogs.com/qiantuwuliang/archive/2010/11/03/1867802.html 可能做程序的人都知道,float类型是可以存浮点数(即 ...
- MD5Helper辅助类
DES加密和解密 public class MD5Helper { ///DES加密 ///sKey public string MD5Encrypt(string pToEncrypt, strin ...
- Java---俄罗斯方块小游戏
去年就已经学了这个技术了,一直没去写,现在抽个时间写了个俄罗斯方块游戏. 只有简单的新游戏,暂停,继续,积分功能.简单的实现了俄罗斯的经典功能. 不介绍了,有兴趣的自己运行一下,后面贴出了图片. 代码 ...
- How to create XML validator(验证器;验证程序) from XML schema
In order to check XML data for validity we have to prepare its schema XSD-file. This file will be lo ...
- db2 identity列重置,reset/restart
db2中可以对表中的某一个列创建identity列,用于自动填充值,某些情况下(比如删除数据后,需要从最小值开始,并不重复,那可以对标识列进行reset操作) 语法: ALTER TABLE < ...