动态更改属性属性

问题描述 投票:1回答:2

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
matlab properties attributes private-members
2个回答
3
投票

Access级别是固定的,就像我所知道的任何OOP语言一样。它是如何与其他代码交互的基础。

您唯一的解决方法是使用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

产量

>> A = POC(1);
l>> A.prop
Error using POC/get.prop (line 17)
Property "prop" not accessible when POC.arg == 1 
>> A = POC(2);
>> A.prop
ans =
    'some value'

0
投票

编辑:我创建了两个不同的类,一个隐藏,一个隐藏属性。

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

properties (Dependent = true, Hidden = True, GetAccess=private, SetAccess=private)
© www.soinside.com 2019 - 2024. All rights reserved.