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