如何在类中实现克隆和复制方法? [英] How to Implement Clone and Copy method inside a Class?

查看:21
本文介绍了如何在类中实现克隆和复制方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Employee 的类,它有 3 个名为 IDNameDept 的属性.我需要实现 CopyClone 方法吗?当我使用 CopyClone 方法时,我需要避免强制转换吗?我该怎么做呢?

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.

这篇关于如何在类中实现克隆和复制方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆