How to define a shared SetMethod for multiple dynamic properties?

2 vues (au cours des 30 derniers jours)
Andrew Joslin
Andrew Joslin le 23 Août 2016
I am implementing a class which must allow dynamic properties to be added and their values modified at will by the user. There is no way to tell what the name of the property will be beforehand, or how many dynamic properties will be added, so I want to use the same SetMethod for all dynamic properties.
Here's the problem: when the SetMethod is invoked, its only input arguments are the object and the value that I'm trying to set the dynamic property to - I can't find any way to pass the name of the property to the SetMethod. I've tried passing the name of the dynamic property into the SetMethod via the function handle, but Matlab complains that there are "Too many input arguments" whenever I do this.
The documentation alludes to shared access methods for dynamic properties in this page, but unfortunately there are no examples: http://www.mathworks.com/help/matlab/matlab_oop/access-methods-for-dynamic-properties.html
This code demonstrates the issue:
classdef MyClass < dynamicprops
properties
end
methods
function mc = MyClass(prop_name,prop_data)
% Return if no arguments
narginchk(0,2);
if nargin < 2
return;
end
% Add a dynamic property
p = addprop(mc,prop_name);
p.SetMethod = @(x)dataSetter(prop_name); % Trying to pass in the property name, so that the "dataSetter" method can be used to set more than one dynamic property
% Set the property value
mc.(prop_name) = prop_data; % This calls the SetMethod "dataSetter"
end
function dataSetter(mc,prop_name,prop_data)
% Do some data validation here
%
% Do some fancy stuff here
%
% Set the property value
mc.(prop_name) = prop_data;
% Do some other stuff here
%
end
end
end
With that class implemented, I get this:
>> mc = MyClass('tmp','test')
Error using MyClass>@(x)dataSetter(prop_name)
Too many input arguments.
Error in MyClass (line 20)
mc.(prop_name) = prop_data; % This calls the SetMethod "dataSetter"
20 mc.(prop_name) = prop_data; % This calls the SetMethod "dataSetter"
I'm using Matlab r2013b.
Thanks!!!

Réponse acceptée

Andrew Joslin
Andrew Joslin le 23 Août 2016

Plus de réponses (0)

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!

Translated by