动态更改属性属性

时间:2019-03-20 12:16:52

标签: matlab properties attributes private-members

在A类中有依赖的属性,基于构造函数中的一个参数,我想隐藏一些属性,以使用户无法设置/获取这些属性。

classdef A
    properties (Dependent = true)
        prop1
        prop2
    end

    methods
        function value = get.prop1(obj)
        ...
        end
        function value = get.prop2(obj)
        ...
        end
    end

    methods(Access = public)
         function obj = A(arg1)
             if arg1 == 1
                  % make prop1 Hidden for the constructed object
             end
         end
    end
end

这是示例用法:

a1 = A(2);
a1.prop1;   % ok
a2 = A(1);
a2.prop1;   % problem, user will not know about existence prop1

2 个答案:

答案 0 :(得分:3)

{% for block in page.content %} <!-- {% cycle 'right' 'left' as position %} {% cycle 'primary' 'secondary' 'white' as color %} --> {% include_block block with pos=position color=color %} {% endfor %} 级别是固定的,就像我所知道的任何OOP语言一样。该类如何与其他代码交互基本

您唯一的解决方法是使用Access类型类的Dependent属性,并根据构造参数具有条件行为。这是一个matlab.mixin.SetGet类来演示:

班级

POC

输出

classdef POC < matlab.mixin.SetGet
    properties ( Dependent = true )
        prop
    end
    properties ( Access = private )
        arg   % Construction argument to dictate obj.prop behaviour
        prop_ % Private stored value of prop
    end
    methods
        function obj = POC( arg )
            % constructor
            obj.prop = 'some value'; % Could skip setting this if argCheck fails
            obj.arg = arg;
        end

        % Setter and getter for "prop" property do obj.argCheck() first.
        % This throws an error if the user isn't permitted to set/get obj.prop
        function p = get.prop( obj )
            obj.argCheck();
            p = obj.prop_;
        end
        function set.prop( obj, p )                
            obj.argCheck();
            obj.prop_ = p;
        end
    end
    methods ( Access = private )
        function argCheck( obj )
            % This function errors if the property isn't accessible
            if obj.arg == 1
                error( 'Property "prop" not accessible when POC.arg == 1' );
            end
        end
    end
end

答案 1 :(得分:0)

编辑:我将创建两个不同的类,一个具有隐藏属性,一个具有可见属性。

在这种情况下,您只需在隐藏类中设置相应的属性即可。应该这样做:

properties (Dependent = true, Hidden = True, GetAccess=private, SetAccess=private)