我正在编写一个类定义,它在设置某些属性时使用侦听器来修改对象。像这样:
classdef MyObject < handle
properties (SetObservable)
orientation = 'h'; % h = horizontal, v = vertical, o = other
length
width
end
methods
% Constructor
function mo = MyObject(o)
mo.orientation = o;
addlistener(mo, 'orientation', 'PreSet', @mo.changeOrientation);
end
% Change Orientation Listener
function changeOrientation(mo, src, evnt)
celldisp(src);
celldisp(evnt);
% I want a way to access newor here
if mo.orientation == 'h' && newor == 'o'
tempw = mo.width
mo.width = mo.length
mo.length = tempw;
end
end
% Setter
function set.orientation(mo, newor)
mo.orientation = newor;
end
end
end
我希望能够在设置方向时使用变量 newor。如何将新的方向变量传递给 changeOrientation 方法?
我想避免将 的内容移动changeOrientation
到set.orientation
方法中,因为 Matlab 抱怨属性(长度和宽度)可能没有被初始化。
EDIT 长度不依赖于方向。当方向改变时,我只需要交换长度和宽度。在其他情况下,用户应该能够将长度或宽度设置为任何正值。