How to Implement Clone and Copy method inside a Class?(如何在类中实现克隆和复制方法?)
问题描述
我有一个名为 Employee 的类,它有 3 个名为 ID、Name、Dept 的属性.我需要实现 Copy 和 Clone 方法吗?当我使用 Copy 或 Clone 方法时,我需要避免强制转换吗?我该怎么做呢?
I have class called Employee with 3 property called ID,Name,Dept. I need to implement the Copy and Clone method? When I am using Copy or Clone method I need to avoid Casting? how will I do that?.
示例:与具有 DataTable.Copy() 和 DataTable.Clone() 的 DataTable 相同.
example: same as DataTable which is having DataTable.Copy() and DataTable.Clone().
推荐答案
你需要实现IClonable接口并提供clone方法的实现.如果你想避免强制转换,不要实现这个.
You need to implement IClonable interface and provide implementation for the clone method. Don't implement this if you want to avoid casting.
一个简单的深度克隆方法可能是将对象序列化到内存然后反序列化它.您的类中使用的所有自定义数据类型都需要使用 [Serializable] 属性进行序列化.对于克隆,您可以使用类似
A simple deep cloning method could be to serialize the object to memory and then deserialize it. All the custom data types used in your class need to be serializable using the [Serializable] attribute. For clone you can use something like
public MyClass Clone()
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, this);
ms.Position = 0;
object obj = bf.Deserialize(ms);
ms.Close();
return obj as MyClass;
}
如果你的类只有 值类型,那么你可以使用一个 复制构造函数 或者只是将值分配给Clone 方法中的一个新对象.
If your class only has value types, then you can use a copy constructor or just assign the values to a new object in the Clone method.
这篇关于如何在类中实现克隆和复制方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在类中实现克隆和复制方法?
基础教程推荐
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 如果条件可以为空 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
