Setter methods for dynamic properties
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello,
I have been working with a class that has dynamic properties that I would like to have setter methods for. The problem is that I don't know how many or the names of the dynamic properties, so I want to have just one setter that takes the name of the property as an argument. However this breaks the part of MATLAB that determines whether or not you're in a setter function (so that when you set the variable it just sets the variable, instead of calling the setter recursively). Here's some example code that illustrates what I'm talking about:
classdef myClass < dynamicprops
methods
function obj = myClass()
P = addprop(obj, 'myProp');
P.SetMethod = @(o,p)SetProp(o,'myProp',p);
end
function SetProp(obj, propname, val)
obj.(propname) = val;
end
end
end
Now if you try:
x = myClass();
x.myProp = 7;
the method SetProp gets called recursively until MATLAB throws an error. Is there another way to go about this that I am missing? Thanks in advance.
-Andrew
3 commentaires
Réponse acceptée
Daniel Shub
le 19 Sep 2012
What about overloading subsasgn
classdef myClass < dynamicprops
methods
function obj = myClass()
P = addprop(obj, 'myProp');
end
function A = subsasgn(A, S, B)
switch S.type
case '.'
SetProp(A, S.subs, B);
end
end
function SetProp(obj, propname, val)
obj.(propname) = val;
end
end
end
2 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Properties dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!