How do I write a common set method for multiple properties

조회 수: 14 (최근 30일)
Kristina Kossarev
Kristina Kossarev 2021년 3월 30일
댓글: per isakson 2021년 4월 1일
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
Kristina Kossarev
Kristina Kossarev 2021년 4월 1일
Thanks for the answer! Can you specify how you wouldoverwrite it? I tried to overwrite subsasgn based on the MatWorks documentation but I still get the same recursion error:
methods(Access = protected)
function mc = commonSetter(mc, value, property)
% do some stuff
disp('Made it into the commonSetter!')
% mc.(property) = value;
S = struct('type', '.', 'subs', property);
mc = subsasgn(mc, S, value);
end
function obj = subsasgn(obj,s,varargin)
% Allow subscripted assignment to uninitialized variable
if isequal(obj,[])
obj = MyClass.empty;
end
switch s(1).type
case '.'
if length(s) == 1
prop = s(1).subs; % Property name
n = numel(obj); % Number of elements in array
for k = 1:n
obj(k).(prop) = varargin{k};
end
else
% Call built-in for any other case
obj = builtin('subsasgn',obj,s,varargin{:});
end
otherwise
error('Not a valid indexing expression')
end
end
end
per isakson
per isakson 2021년 4월 1일
My comment was definately not meant as an answer. That's why I posted it as a comment.

댓글을 달려면 로그인하십시오.

답변 (1개)

Kristina Kossarev
Kristina Kossarev 2021년 4월 1일
The question was answered in stackoverflow

카테고리

Help CenterFile Exchange에서 Customize Object Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by