7

在 MATLAB 2008a 中,有没有办法允许类方法充当 uicontrol 回调函数,而无需公开该方法?从概念上讲,该方法不应该是公共的,因为它不应该被类的用户调用。它只能在 UI 事件触发回调时调用。但是,如果我将方法的访问权限设置为私有或受保护,则回调不起作用。我的类派生自 hgsetget 并使用 2008a classdef 语法定义。

uicontrol 代码如下所示:


methods (Access = public)
   function this = MyClass(args)
      this.someClassProperty = uicontrol(property1, value1, ... , 'Callback', ...
      {@(src, event)myCallbackMethod(this, src, event)});
      % the rest of the class constructor code
   end
end

回调代码如下所示:


methods (Access = private)  % This doesn't work because it's private
   % It works just fine if I make it public instead, but that's wrong conceptually.
   function myCallbackMethod(this, src, event)
      % do something
   end
end
4

1 回答 1

8

将回调的函数句柄存储为私有属性似乎可以解决该问题。试试这个:

classdef MyClass
    properties
        handle;
    end

    properties (Access=private)
        callback;
    end

    methods
        function this = MyClass(args)
            this.callback = @myCallbackMethod;
            this.handle = uicontrol('Callback', ...
                {@(src, event)myCallbackMethod(this, src, event)});
        end
    end

    methods (Access = private)
        function myCallbackMethod(this, src, event)
            disp('Hello world!');
        end
    end
end
于 2008-09-22T08:10:20.297 回答