How to Implement Clone and Copy method inside a Cl

2019-01-22 21:21发布

问题:

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

example: same as DataTable which is having DataTable.Copy() and DataTable.Clone().

回答1:

You need to implement IClonable interface and provide implementation for the clone method. Don't implement this if you want to avoid casting.

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

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.



回答2:

Do you have to use the ICloneable interface or is it enough if you just have two methods called Clone and Copy that is defined in a generic interface?

public class YourClass : ICloneable<YourClass>
{
    // Constructor logic should be here
    public YourClass Copy() { return this; }        
    public YourClass Clone() { return new YourClass(ID, Name, Dept); }
}

interface  IClonable<T>
{
    T Copy();
    T Clone();
}

Or have I misunderstood something?

What I am trying to say is that you don't have to make it more complex than it is? If you need your objects to conform to somekind of you can write it yourself if the one specified in the .Net framework is to complex for the situation. You should also define the difference with Clone and Copy, that is, what do they mean to you? I know there are several sites specifying that Clone is a deep copy and Copy is a shallow copy.



回答3:

Do you mean, how to implement ICloneable.Clone() and have it return the type of the class itself.

public class MyType : ICloneable
{
  public MyType Clone() //called directly on MyType, returns MyType
  {
    return new MyType(/* class-dependant stuff goes here */);
  }
  object ICloneable.Clone() // called through ICloneable interface, returns object
  {
    return Clone();
  }
}


回答4:

Check this Object Cloning Using IL in C# http://whizzodev.blogspot.com/2008/03/object-cloning-using-il-in-c.html



回答5:

I often see copy constructors suggested as an alternative to a cloning method, but except with sealed classes the behaviors are very different. If I have a type Car, which simply supports properties VIN, BodyColor and BodyStyle, and a derivative type FancyCar, which also supports InteriorFabric and SoundSystem, then code which accepts an object of type Car and use the Car copy constructor to duplicate it will end up with a Car. If a FancyCar is passed to such code, the resulting "duplicate" will be a new Car, which has a VIN, BodyColor, and BodyStyle that match the original car, but which will not have any InteriorFabric or SoundSystem. By contrast, the code were to accept a Car and use a cloning method on it, passing a FancyCar to the code would cause a FancyCar to be produced.

Unless one wants to use Reflection, any cloning method must at its base involve a call to base.MemberwiseClone. Since MemberwiseClone is not a virtual method, I would suggest defining a protected virtual cloning method; you may also want to prevent any child classes from calling MemberwiseClone by defining a dummy nested class of protected scope with the same name (so if a descendent class tries to call base.MemberwiseClone, it wouldn't be interpreted as a nonsensical reference to the dummy class).



回答6:

Here an example:

namespace XXX
{
     [Serializable]
    public class ItemChecklist : ICloneable
    {

       // [...here properties, attributes, etc....]



        object ICloneable.Clone()
        {
            return this.Clone();
        }
        public ItemChecklist Clone()
        {
            return (ItemChecklist)this.MemberwiseClone();
        }


    }
}

i.e If you use this function, you will have in "itemAdd" a entire copy of the object "itemTemp" with all its values.

ItemChecklist itemAdd = itemTemp.Clone();