在具有依赖属性c
的类中,我想使用等于c
或'a'
的第三个参数调用'b'
的setter,选择哪个独立要更改的属性以设置c
。
代码是
classdef test < handle
properties
a
b
end
properties (Dependent = true)
c
end
methods
function c = get.c(obj)
c = obj.a + obj.b;
end
function obj = set.c(obj, value, varargin)
if(nargin == 2)
obj.a = value - obj.b;
end
if(nargin == 3 && argin(3) == 'a') % how do I enter this loop?
obj.a = value - obj.b;
end
if(nargin == 3 && argin(3) == 'b') % or this?
obj.b = value - obj.a;
end
end
end
end
此通话有效:
myobject.c = 5
但如何使用等于'a'
或'b'
的第三个参数调用setter?
答案 0 :(得分:0)
你做不到。 set
始终只接受两个参数。你可以使用额外的依赖属性解决它:
classdef test < handle
properties
a
b
end
properties (Dependent = true)
c
d
end
methods
function c = get.c(obj)
c = obj.a + obj.b;
end
function d = get.d(obj)
d = c;
end
function obj = set.c(obj, value)
obj.a = value - obj.b;
end
function obj = set.d(obj, value)
obj.b = value - obj.a;
end
end
end
或选择不同的语法和/或方法:
myObject.set_c(5,'a') %// easiest; just use a function
myObject.c = {5, 'b'} %// easy; error-checking will be the majority of the code
myObject.c('a') = 5 %// hard; override subsref/subsasgn; good luck with that
或其他创意:)