0

Matlab 类属性有以下两个与我的问题相关的限制,

  1. 依赖属性不能存储值
  2. 属性的设置器(没有指定属性、访问说明符等的普通属性)无法访问其他属性。

在我的场景中,我需要一种解决方法,它允许我拥有一个也可以存储价值的依赖属性。对另一个属性的依赖仅用于条件语句,而不是用于将其值与其他属性本身一起分配。下面给出的代码片段说明了这种情况,这也是我的 Matlab 不允许的要求。

classdef foo
properties
    a
    b
end
properties (Dependent = true)
    c
end
methods
    function this = foo(c_init)
        a = 1;
        b = 1;
        this.c = c_init;
    end
    function this = set.c(this,value)
        if b==1
            c = value;
        else
            c = 1;
        end
    end
    function value = get.c(this)
        value = this.c;
    end
end
end

以上有什么解决方法吗?

4

1 回答 1

3

首先,您绝对可以让一个属性集函数访问另一个属性的值,只是不完全推荐,因为该其他属性的有效性是未知的,尤其是在对象创建期间。这将发出一个 mlint 警告。另外我相信,如果设置器用于依赖属性,则不存在此 mlint 警告。

要执行您正在尝试的操作(在 Dependent 属性中“存储”一个值),您可以创建一个“影子”属性,c该属性是私有的,用于存储c. 在下面的示例中,我使用c_了下划线来表示它是一个阴影属性。

 classdef foo
    properties
        a
        b
    end

    properties (Dependent = true)
        c
    end

    properties (Access = 'private')
        c_
    end

    methods
        function this = foo(c_init)
            this.a = 1;
            this.b = 1;
            this.c_ = c_init;
        end

        function this = set.c(this, value)
            if this.b ~= 1
                value = 1;
            end

            this.c_ = value;
        end

        function value = get.c(this)
            value = this.c_;
        end
    end
end

另外,我不完全确定您的帖子是否是您尝试做的过于简化的版本,但是对于您提供的示例,您可以很容易地制作c 依赖属性,而只需定义一个自定义设置器。

classdef foo
    properties
        a
        b
        c
    end

    methods
        function this = foo(c_init)
            this.a = 1;
            this.b = 1;
            this.c = c_init;
        end

        function this = set.c(this, value)
            if this.b ~= 1
                value = 1;
            end

            this.c = value;
        end
    end
end
于 2016-02-17T21:08:21.540 回答