Avoid warning “a set method for non-dependent property should not access …”

后端 未结 1 1467
别跟我提以往
别跟我提以往 2021-01-22 12:26

I have a class which has some properties and 2 are related, in the example called param1, param2. They are independent, just constrained. param2 must b

相关标签:
1条回答
  • 2021-01-22 13:16

    You could use two layers of properties

    • one layer which is exposed and Dependent
    • one layer which is private and actually stores the values

    The similar technique is used here in the documentation: Avoid Property Initialization Order Dependency.

    classdef TestClass < handle  
        properties (Access = private)
            privateParam1;
            privateParam2;
        end
    
        properties (Dependent)
             param1;
             param2;
        end
    
        methods
            function p1 = get.param1(obj)
                p1 = obj.privateParam1;
            end
    
            function p2 = get.param2(obj)
                p2 = obj.privateParam2;
            end
    
            function set.param1(obj, input)
                obj.privateParam1 = input;
                if (isempty(obj.privateParam2) || obj.privateParam2 < obj.privateParam1)
                    obj.privateParam2 = obj.param1; 
                end
            end
    
             function set.param2(obj, input)
                if (~isempty(obj.privateParam1) && obj.privateParam1 > input)
                    obj.privateParam2 = obj.privateParam1;
                else
                    obj.privateParam2 = input;
                end
             end
        end
    end
    

    The trick here: privateParam1 and privateParam2 stores the two values. The get and set only implemented for the exposed properties param1 and param2: the get returns simply the inner property and in the set both of them can be used without the analyzer warning as they are marked as Dependent.

    0 讨论(0)
提交回复
热议问题