Ho to copy an object (deep copy) which has inside another object

26 次查看(过去 30 天)
Hi,
I have an object (obj1) with the following properties:
PipeName
PipeVault
UnLock
Units
However the PipeVault is also an object (obj2) with the properties:
Name;
Value;
When I make a copy (deep copy) of the object (obj1) I get: obj1Copy and if I change one property like (obj1.PipeName) this change only affect the obj1.PipeName but not the obj1Copy.PipeName which is fine and is what I need. However if I change the property (obj1.PipeVault. Name) the obj1Copy.PipeVault. Name also change. Both classes (of obj1 and obj2) employ the matlab.mixin.Copyable. Therefore I expected the same behavior as for the obj1.PipeName. How can I make a deep copy of obj1 and I get a totally independent object obj2 ( that is if I change obj1.PipeVault. Name this would not change obj2.PipeVault. Name)
Kind regards,
Armindo

采纳的回答

Guillaume
Guillaume 2016-2-15
As per its documentation matlab.mixin.Copyable does not make a deep copy of the object properties even if they themselves derived from copyable: "In making a shallow copy, MATLAB® does not call copy recursively on any handles contained in property values." You actually have to override the copyElement to make the copy yourself:
classdef Pipe < matlab.mixin.Copyable
properties
PipeName;
PipeVault;
UnLock;
Units;
end
methods (Access = protected)
function thiscopy = copyElement(this)
thiscopy = copyElement@matlab.mixin.Copyable(this); %shallow copy of all elements
thiscopy.PipeVault = copy(this.PipeVault); %Deep copy of pipevault
end
end
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Handle Classes 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by