【问题标题】:Constructor executed when property get method executed执行属性获取方法时执行的构造函数
【发布时间】:2017-01-01 06:25:53
【问题描述】:

我想子类化内置控件,例如axes;但是,据我所知,MATLAB 不允许以有记录的方式这样做。为了解决这个问题,我创建了一个名为 MyAxes 的类,如下所示。

MyAxes 有一个名为MATLABAxes 的已定义属性,它存储一个matlab.graphics.axis.Axes 对象。此坐标区对象是在构造时创建的。每个坐标区属性都会动态添加到正在构造的 MyAxes 对象中,从而创建包装器属性,这些属性应该简单地重定向到 MATLABAxes 属性。

每个包装器属性的get 方法都设置为MyAxes 的方法get_axes_property。此方法接受三个参数:

  1. MyAxes 对象本身
  2. 对轴控件的引用
  3. 属性名称

此方法效果很好,只是它为每个属性创建了一个新轴。我最终得到一个有 131 个子轴的图形!这似乎是因为在 MyAxes 构造函数中创建了轴。解决此问题的方法是要求首先创建 MATLAB 坐标区并将其作为参数传递给构造函数。这很不方便。

如何在MyAxes 构造函数中维护轴创建而不创建多个轴?当然,如果我偏离了轨道并且有更好的方法对内置控件进行子类化,我很想听听。

classdef Axes < handle & dynamicprops

    properties
        MATLABAxes;
    end

    methods

        function obj = Axes
            obj.MATLABAxes = axes;
            axesPropertyList = properties( obj.MATLABAxes );
            for property = axesPropertyList(:)'
                propertyName = property{1};
                obj.addprop( propertyName );
                propertyInstance = obj.findprop( propertyName );
                propertyInstance.GetMethod = @(x,y)obj.get_axes_property( obj.MATLABAxes, propertyName );
            end
        end

        function value = get_axes_property( obj, control, propertyName )
            value = control.(propertyName);
        end

    end

end

【问题讨论】:

    标签: matlab oop inheritance


    【解决方案1】:

    又做了一次 - 在写问题时回答了我自己的问题。这是一个拼写错误。我在函数句柄定义中将get_axes_property 方法的第一个参数设置为axes 而不是obj.MATLABAxes。每次获取属性时,它都会执行axes 函数。问题中的代码现已修复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-13
      • 2015-12-18
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      相关资源
      最近更新 更多