How do I write 'setter' methods for properties with unknown names?
3 ビュー (過去 30 日間)
古いコメントを表示
MathWorks Support Team
2016 年 2 月 4 日
回答済み: MathWorks Support Team
2016 年 2 月 4 日
The following class cannot be initialized, as any call to the constructor gives the error:
>> MyClass('a',2)
Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N) to change the limit. Be aware that exceeding your available
stack space can crash MATLAB and/or your computer.
Error in MyClass/MyClass/@(o,p)setProp(o,propname,p)
classdef MyClass < dynamicprops
methods
function obj = MyClass(propname, val)
P = obj.addprop(propname);
P.SetMethod = @(o,p)setProp(o,propname,p);
obj.(propname) = val;
end
function setProp(obj, propname, val)
% do other stuff, like evaluating if val is legitimate
obj.(propname) = val;
end
end
end
Why is this, and what is the best way to write custom 'set' methods for dynamic properties with unknown names?
採用された回答
MathWorks Support Team
2016 年 2 月 4 日
The infinite recursion is caused by the line 'obj.(propname) = val;' in setProp. This calls the SetMethod for the property 'propname'. When setting the value of a property, MATLAB checks to see if you are currently in the SetMethod for that property in order to avoid infinite recursion. However, since your SetMethod is an anonymous function which calls setProp (and not setProp itself), this assignment is not inside the SetMethod, and the assignment calls the anonymous function.
To avoid this issue, you may use a nested function as shown below:
% start of file MyClass2.m
classdef MyClass2 < dynamicprops
methods
function obj = MyClass2(propname, val)
P = obj.addprop(propname);
P.SetMethod = propSetFcn(obj, propname);
obj.(propname) = val;
end
end
end
function f = propSetFcn(obj, propname)
function setProp(obj, val)
% do other stuff
obj.(propname) = val;
end
f = @setProp;
end
% end of file MyClass2.m
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Argument Definitions についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!