似乎MATLAB句柄不会同时响应来自同一来源的多个通知。不幸的是,这对我来说是个大问题。下面是我正在讨论的一个例子:
classdef testClass < handle
events
testevent
end
methods
function obj = testClass
obj.addlistener('testevent', @obj.respond);
end
function raise(obj)
obj.notify('testevent');
end
function respond(obj, varargin)
fprintf('Responded!\n');
obj.raise();
end
end
end当我执行代码时
c = testClass;
c.raise();结果是
Responded!但是我真的希望递归能够工作,尽管很明显在这个简单的例子中它会无限地递归。有什么方法可以获得这种行为吗?
发布于 2011-09-14 06:34:15
通过将监听器句柄的Recursive属性设置为true,可以使该监听器成为递归的。Listener handle properties are in the event.listener help page。您只需为obj.addlistener指定一个输出参数即可检索句柄。
下面是我用来让它工作的代码:
classdef testClass < handle
events
testevent
end
methods
function obj = testClass
lh = obj.addlistener('testevent', @obj.respond);
lh.Recursive = true;
end
function raise(obj)
notify(obj,'testevent');
end
function respond(obj, varargin)
fprintf('Responded!\n');
obj.raise();
end
end
end还要注意,默认的递归限制是500次调用,所以代码不会无限地重复;使用set(0, 'RecursionLimit', N)来改变这一点。我认为设置N=inf不是一个好主意。
https://stackoverflow.com/questions/7409238
复制相似问题