C # simplifies and possibly generalizes the method of cloning objects

I wrote a method:

class CopyableFloatCommand : FloatCommand
{
    public CopyableFloatCommand DeepCopy(LocationHeaderDTO locHeader, string commandId,
        List<FloatProductDetailsDTO> recountProuducts)
    {
        var newCommand = (CopyableFloatCommand)MemberwiseClone();
        newCommand.Location = locHeader ?? newCommand.Location;
        newCommand.CommandId = commandId ?? newCommand.CommandId;
        newCommand.RecountProducts = recountProuducts ?? newCommand.RecountProducts;
        return newCommand;
    }
}

And then I call it through:

_tCheckinCommand = _pTCommand.DeepCopy(stagingLocHeadDto, SCICommand,
    new List<FloatProductDetailsDTO>(_pTCommand.MoveProducts));

To deep copy an object of type FloatCommand.

Since the MemberwiseClone () method is protected, it must be called as you see above - you cannot use parsing of the FloatCommand type in the method parameter and call it through fc.MemberwiseClone (), for example. Since my method should work on the FloatCommand type, I created a new nested CopyableFloatCommand class that inherits from FloatCommand. The DeepCopy method then shallowly clones the FloatCommand, discards the child type, and changes some properties as necessary.

, . , , ? , UserCommand User? UserComand FloatCommand, Command. , ( , ), .

DeepCopy, , , ?

!

+4
1

, , - ( UserCommand).

:

:

public interface ICopyCommandMutation
{
  void Mutate(Command target); 
}

muate:

public class NoMutation : ICopyCommandMutation
{
  public void Mutate(Command target) {}
}

CopyableCommand DeepCopy() ( FloatCommand CopyableCommand):

public CopyableCommand : Command 
{
   public CopyableCommand DeepCopy(ICopyCommandMutation commandMutation = null)
   {
      var newCommand = (CopyableCommand)MemberwiseClone();
      if (commandMutation == null) commandMutation = new NoMutation();
      commandMutation.Mutate(newCommand);
      return newCommand;
   }
}

CopyableCommand "" - . , FloatCommand :

public class ChangeLocationRecountProducts : ICopyCommandMutation
{
  // these fields should be initialized some way (constructor or getter/setters - you decide
  LocationHeaderDTO locHeader;
  string commandId;
  List<FloatProductDetailsDTO> recountProducts;

  public void Mutate(Command floatCommand)
  {
     var fc = floatCommand as FloatCommand;
     if (fc == null) { /* handle problems here */ }
     fc.Location = locHeader ?? fc.Location;
     fc.CommandId = commandId ?? fc.CommandId;
     fc.RecountProducts = recountProuducts ?? fc.RecountProducts;
  }
}

:

var clrp = new ChangeLocationRecountProducts();
// ... setting up clrp
_tCheckinCommand = _pTCommand.DeepCopy(clrp);

, "" UserCommand, . ( ) . , , - , , , CopyableCommand ( ?). - Castle.

Automapper, , - .

" ", , .

+1

Source: https://habr.com/ru/post/1663171/


All Articles