假设我有以下课程:
classdef myClass
properties
Globals = struct(...
'G1', 1, ...
'G2', 2 ...
);
end
methods
% methods go here
end
end
Run Code Online (Sandbox Code Playgroud)
我使用struct,因为还有其他属性是结构.
有没有办法为结构域提供一个setter?天真地提供
function obj = set.Globals.G1(obj, val)
obj.Globals.G1 = val; % for example
end
Run Code Online (Sandbox Code Playgroud)
不起作用.
您必须为整个结构定义设置方法(见下文)。或者,您可以为“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
Run Code Online (Sandbox Code Playgroud)