【问题标题】:MATLAB - Update private property in case of other property changeMATLAB - 在其他属性更改的情况下更新私有属性
【发布时间】:2018-05-09 14:07:37
【问题描述】:

我有一个具有依赖属性的类,需要一段时间才能进行评估。出于这个原因,我不希望每次查询时都对其进行评估,而仅在实例化对象和更改某些属性时才评估它。我发现 this interesting solution 是基于定义一个额外的私有属性,该属性在必要时设置,依赖属性采用这个额外的私有属性的值。

现在的问题是:如何确保在实例化对象时设置此私有属性,并在更改对象的某些属性时自动更新?

【问题讨论】:

    标签: matlab oop properties dependencies private


    【解决方案1】:

    建议的解决方案是完美的,只需确保在您的类构造函数中定义依赖属性及其代理的默认值都设置为适合您需要的默认值:

    methods
        function this = MyClass(...)
            % default starting values for your properties 
            this.MyProperty1 = 0;
            this.MyProperty2 = -8;
            this.MyProperty3 = 3;
    
            % calculate the initial value of your dependent
            % property based on the default values of the other
            % properties (this is basically the computeModulus
            % function of your example)
            this.UpdateMyDependent();
        end
    end
    

    当其他属性被修改时使你的依赖属性更新的逻辑已经包含在链接线程中,在你的类中实现它们。

    function this = set.MyProperty1(this,value)
        this.MyProperty1 = value;
        this.UpdateMyDependent();
    end
    
    function this = set.MyProperty2(this,value)
        this.MyProperty2 = value;
        this.UpdateMyDependent();
    end
    
    function UpdateMyDependent(this)
        this.MyDependentProxy = this.MyProperty1 * this.MyProperty2;
    end
    
    function value = get.MyDependent(this)
        value = this.MyDependentProxy;
    end
    

    【讨论】:

      猜你喜欢
      • 2019-08-25
      • 1970-01-01
      • 2020-11-24
      • 2017-11-20
      • 1970-01-01
      • 2015-09-27
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多