How do I write a common set method for multiple properties
Afficher commentaires plus anciens
I work within a project which has several classes which define properties that use essentially the same set method. To make the code more readable, I want to implement a commonsetter method. The overall goal is to include this commonsetter method in the superclass, so that all the classes could use it. Here is a minimum example:
classdef MyClass
properties
A
B
end
methods
function mc = MyClass(a,b) % Constructor
mc.A = a;
mc.B = b;
end
function mc = set.A(mc, value) % setter for A
mc = mc.commonSetter(value, 'A');
end
function mc = set.B(mc, value) % setter for B
mc = mc.commonSetter(value, 'B');
end
end
methods(Access = protected)
function mc = commonSetter(mc, value, property)
% do some stuff
disp('Made it into the commonSetter!')
mc.(property) = value;
end
end
end
% tested with MyClass(1,2)
Unfortunatelly, I get following error: Maximum recursion limit of 500 reached.
My questions would be: Is there a way to use the commonsetter function for variables A and B? And what do I have to change if I want to include this commonsetter method in the superclass?
3 commentaires
per isakson
le 1 Avr 2021
There is an infinite loop. mc.(property) = value; calls set.A (or set.B), which in turn calls commonSetter.
To break that loop I guess you should look at builtin() and subsasgn(). Maybe Overriding subsref and subsasgn - effect on private properties can be of some help.
Kristina Kossarev
le 1 Avr 2021
per isakson
le 1 Avr 2021
My comment was definately not meant as an answer. That's why I posted it as a comment.
Réponses (1)
Kristina Kossarev
le 1 Avr 2021
0 votes
Catégories
En savoir plus sur Customize Object Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!