假设我有以下课程:
classdef myClass
properties
Globals = struct(...
'G1', 1, ...
'G2', 2 ...
);
end
methods
% methods go here
end
end
我使用struct,因为还有其他属性是结构。
有没有办法为结构字段提供setter?天真地提供
function obj = set.Globals.G1(obj, val)
obj.Globals.G1 = val; % for example
end
不起作用。
答案 0 :(得分:4)
您必须为整个结构定义set方法(参见下文)。或者,您可以为“Globals”定义一个类,它看起来和感觉就像一个用于大多数实际目的的结构(除了您不能拼写字段名称),并且可以为其属性实现自己的set / get方法。
function obj = set.Globals(obj,val)
%# look up the previous value
oldVal = obj.Globals;
%# loop through fields to check what has changed
fields = fieldnames(oldVal);
for fn = fields(:)' %'#
%# turn cell into string for convenience
field2check = fn{1};
if isfield(val,field2check)
switch field2check
case 'G1'
%# do something about G1 here
case 'G2'
%# do something about G2 here
otherwise
%# simply assign the fields you don't care about
obj.Globals.(field2check) = val.(field2check);
end
end
end
end %# function