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.
这篇关于如何在类中实现克隆和复制方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在类中实现克隆和复制方法?


- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01