如何实现一个类里面的克隆和复制的方法? [英] How to Implement Clone and Copy method inside a Class?

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

问题描述

我有一个名为员工 3个属性称为类 ID 名称部门。我需要实现复制克隆的方法?当我使用复制克隆方法,我需要避免铸造? ?同数据表由具有数据表:我将如何做到这一点。

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?.

例如.Copy() DataTable.Clone()

推荐答案

<击>您需要实现IClonable接口,并提供实施克隆方法。<如果你想避免铸造/击>不要实现这一点。

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;
    }

如果您的类仅有的value 的类型,那么你可以使用的拷贝构造函数或只是分配值在克隆方法的新对象。

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天全站免登陆